Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

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 it is important that it holds its value. The problem with it is that the controller that initialises it, gets called again by angular somehow 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 it is 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?

1 Answer

0 votes
by (106k points)
edited by

In ANgularJS you have got two options for "global" variables:

  • use a $rootScope 

  • use a service 

Are you interested in learning Angularjs from the basics! Here's the right video for you on Angularjs provided by Intellipaat:

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

Want to learn Angularjs from scratch! Have a look at this video on Angularjs provided by Intellipaat:

Whereas the services are singletons that you can inject to any controller and expose their values in a controller's scope. 

Services are a bit more complex, here is an example regarding the same:-

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; 

}

Enroll in our Angular Certification to become an expert in angular! 

Related questions

0 votes
1 answer
asked Sep 3, 2019 in Web Technology by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...