Questions
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?
Answers
You ve got basically 2 options for "global" variables:
http://c2.com/cgi/wiki?GlobalVariablesAreBad
http://c2.com/cgi/wiki?GlobalVariablesAreBad
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;
}
http://jsfiddle.net/pkozlowski_opensource/BRWPM/2/
http://jsfiddle.net/pkozlowski_opensource/BRWPM/2/
Source
License : cc by-sa 3.0
http://stackoverflow.com/questions/11938380/global-variables-in-angularjs
Related