Global variables in AngularJS

2018-12-31 14:15发布

I have a problem where i'm initialising a variable on the scope in a controller. Then it gets changed in another controller when a user logs in. This variable is used to control things such as the navigation bar and restricts access to parts of the site depending on the type of user, so its important that it holds its value. The problem with it is that the controller that initialises it, gets called again by angular some how and then resets the variable back to its initial value.

I assume this is not the correct way of declaring and initialising global variables, well its not really global, so my question is what is the correct way and is there any good examples around that work with the current version of angular?

12条回答
余欢
2楼-- · 2018-12-31 14:25

You've got basically 2 options for "global" variables:

$rootScope is a parent of all scopes so values exposed there will be visible in all templates and controllers. Using the $rootScope is very easy as you can simply inject it into any controller and change values in this scope. It might be convenient but has all the problems of global variables.

Services are singletons that you can inject to any controller and expose their values in a controller's scope. Services, being singletons are still 'global' but you've got far better control over where those are used and exposed.

Using services is a bit more complex, but not that much, here is an example:

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

and then in a controller:

function MyCtrl($scope, UserService) {
    $scope.name = UserService.name;
}

Here is the working jsFiddle: http://jsfiddle.net/pkozlowski_opensource/BRWPM/2/

查看更多
一个人的天荒地老
3楼-- · 2018-12-31 14:27
// app.js or break it up into seperate files
// whatever structure is your flavor    
angular.module('myApp', [])    

.constant('CONFIG', {
    'APP_NAME' : 'My Awesome App',
    'APP_VERSION' : '0.0.0',
    'GOOGLE_ANALYTICS_ID' : '',
    'BASE_URL' : '',
    'SYSTEM_LANGUAGE' : ''
})

.controller('GlobalVarController', ['$scope', 'CONFIG', function($scope, CONFIG) {

    // If you wish to show the CONFIG vars in the console:
    console.log(CONFIG);

    // And your CONFIG vars in .constant will be passed to the HTML doc with this:
    $scope.config = CONFIG;
}]);

In your HTML:

<span ng-controller="GlobalVarController">{{config.APP_NAME}} | v{{config.APP_VERSION}}</span>
查看更多
冷夜・残月
4楼-- · 2018-12-31 14:30

In the interest of adding another idea to the wiki pool, but what about AngularJS' value and constant modules? I'm only just starting to use them myself, but it sounds to me like these are probably the best options here.

Note: as of the time of writing, Angular 1.3.7 is the latest stable, I believe these were added in 1.2.0, haven't confirmed this with the changelog though.

Depending on how many you need to define, you might want to create a separate file for them. But I generally define these just before my app's .config() block for easy access. Because these are still effectively modules, you'll need to rely on dependency injection to use them, but they are considered "global" to your app module.

For example:

angular.module('myApp', [])
  .value('debug', true)
  .constant('ENVIRONMENT', 'development')
  .config({...})

Then inside any controller:

angular.module('myApp')
  .controller('MainCtrl', function(debug, ENVIRONMENT), {
    // here you can access `debug` and `ENVIRONMENT` as straight variables
  })

From the initial question is actually sounds like static properties are required here anyway, either as mutable (value) or final (constant). It's more my personal opinion than anything else, but I find placing runtime configuration items on the $rootScope gets too messy, too quickly.

查看更多
临风纵饮
5楼-- · 2018-12-31 14:31

Example of AngularJS "global variables" using $rootScope:

Controller 1 sets the global variable:

function MyCtrl1($scope, $rootScope) {
    $rootScope.name = 'anonymous'; 
}

Controller 2 reads the global variable:

function MyCtrl2($scope, $rootScope) {
    $scope.name2 = $rootScope.name; 
}

Here is a working jsFiddle: http://jsfiddle.net/natefriedman/3XT3F/1/

查看更多
裙下三千臣
6楼-- · 2018-12-31 14:33
localStorage.username = 'blah'

If you're guaranteed to be on a modern browser. Though know your values will all be turned into strings.

Also has the handy benefit of being cached between reloads.

查看更多
谁念西风独自凉
7楼-- · 2018-12-31 14:40

I just found another method by mistake :

What I did was to declare a var db = null above app declaration and then modified it in the app.js then when I accessed it in the controller.js I was able to access it without any problem.There might be some issues with this method which I'm not aware of but It's a good solution I guess.

查看更多
登录 后发表回答