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:41

It's actually pretty easy. (If you're using Angular 2+ anyway.)

Simply add

declare var myGlobalVarName;

Somewhere in the top of your component file (such as after the "import" statements), and you'll be able to access "myGlobalVarName" anywhere inside your component.

查看更多
旧人旧事旧时光
3楼-- · 2018-12-31 14:41

You can also do something like this ..

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

function MyCtrl2($scope) {
    var name = $rootScope.$root.name;
}
查看更多
倾城一夜雪
4楼-- · 2018-12-31 14:44

You can also use the environment variable $window so that a global variable declare outside a controller can be check inside a $watch

var initWatch = function($scope,$window){
    $scope.$watch(function(scope) { return $window.globalVar },
        function(newValue) {
            $scope.updateDisplayedVar(newValue);
    });
}

Becareful, the digest cycle is longer with these global values, so it is not always real-timed updated. I need to investigate on that digest time with this configuration.

查看更多
情到深处是孤独
5楼-- · 2018-12-31 14:50

If you just want to store a value, according to the Angular documentation on Providers, you should use the Value recipe:

var myApp = angular.module('myApp', []);
myApp.value('clientId', 'a12345654321x');

Then use it in a controller like this:

myApp.controller('DemoController', ['clientId', function DemoController(clientId) {
    this.clientId = clientId;
}]);

The same thing can be achieved using a Provider, Factory, or Service since they are "just syntactic sugar on top of a provider recipe" but using Value will achieve what you want with minimal syntax.

The other option is to use $rootScope, but it's not really an option because you shouldn't use it for the same reasons you shouldn't use global variables in other languages. It's advised to be used sparingly.

Since all scopes inherit from $rootScope, if you have a variable $rootScope.data and someone forgets that data is already defined and creates $scope.data in a local scope you will run into problems.


If you want to modify this value and have it persist across all your controllers, use an object and modify the properties keeping in mind Javascript is pass by "copy of a reference":

myApp.value('clientId', { value: 'a12345654321x' });
myApp.controller('DemoController', ['clientId', function DemoController(clientId) {
    this.clientId = clientId;
    this.change = function(value) {
        clientId.value = 'something else';
    }
}];

JSFiddle example

查看更多
人间绝色
6楼-- · 2018-12-31 14:50

Please correct me if I'm wrong, but when Angular 2.0 is released I do not believe$rootScope will be around. My conjecture is based on the fact that $scope is being removed as well. Obviously controllers, will still exist, just not in the ng-controller fashion.Think of injecting controllers into directives instead. As the release comes imminent, it will be best to use services as global variables if you want an easier time to switch from verison 1.X to 2.0.

查看更多
余欢
7楼-- · 2018-12-31 14:50

Try this, you will not force to inject $rootScope in controller.

app.run(function($rootScope) {
    $rootScope.Currency = 'USD';
});

You can only use it in run block because config block will not provide you to use service of $rootScope.

查看更多
登录 后发表回答