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?
It's actually pretty easy. (If you're using Angular 2+ anyway.)
Simply add
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.
You can also do something like this ..
You can also use the environment variable
$window
so that a global variable declare outside a controller can be check inside a$watch
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.
If you just want to store a value, according to the Angular documentation on Providers, you should use the Value recipe:
Then use it in a controller like this:
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 thatdata
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":
JSFiddle example
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 theng-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.Try this, you will not force to inject
$rootScope
in controller.You can only use it in run block because config block will not provide you to use service of $rootScope.