简体   繁体   中英

Accessing global variables

I'm trying to set a root scope in my angularjs project so I can access name from anywhere in the HTML (not in an ng-view).

<!DOCTYPE html>
<html lang="en" ng-app="phonecatApp" ng-controller="ApplicationController">

</html>

That encapsulates the entire page

I've loaded in a js file called app.js with the following in;

var phonecatApp = angular.module('phonecatApp', []);
phonecatApp.factory('UserService', function(){
    return {
        name : 'Tom'
    };
})

function ApplicationController($scope, UserService){
    $scope.username = UserService.name
}

And I'm trying to do the following in the index.html:

<a href="#index" class="nav-item name_p_nav">{{username}}</a> 

But it just comes back blank

Edit: fixed typo

You can try something like this. Change the way you have declared controller. And in order to use $scope variable, you have to declare it, probably you should be receiving script error as its not declared, please check in the browser using developer tools to find out exact error.

phonecatApp.controller('ApplicationController',['$scope',function ($scope){
 $scope.username = UserService.name

}]);

I tried to reproduce issue, I quickly created an application and it worked for me! Here, I am posting my sample code, just take a look at the same.

<html lang="en" ng-app="phonecatApp" ng-controller="ApplicationController">
<head>
    <script src="../Scripts/lib/angular.min.js"></script>
    <script src="../Scripts/Application1.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
</head>
<body>
    <a href="#index" class="nav-item name_p_nav">{{username}}</a> 
</body>

Script:

var phonecatApp = angular.module('phonecatApp', []);
phonecatApp.factory('UserService', function(){
return {
        name : 'Tom'
};
})

function ApplicationController($scope, UserService){
$scope.username = UserService.name
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM