Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I store a current user context in AngularJS?

Tags:

angularjs

I have an AuthService, which logs in a user, it returns back a user json object. What I want to do is set that object and have all the changes reflected across the application (logged in/logged out state) without having to refresh the page.

How would I accomplish this with AngularJS?

like image 711
Art Avatar asked Jan 08 '13 00:01

Art


People also ask

What holds the data in an AngularJS application?

Applications in AngularJS are controlled by controllers. Read about controllers in the AngularJS Controllers chapter. Because of the immediate synchronization of the model and the view, the controller can be completely separated from the view, and simply concentrate on the model data.

What is $Watch in angular?

In angularjs $watch() function is used to watch the changes of variables in $scope object. Generally the $watch() function will create internally in angularjs to handle variable changes in application.

Who controls the flow of data in AngularJS application?

All the AngularJS application mainly relies on the controllers to control the flow of data in that application. Basically, it controls the data of AngularJS applications and the controller is a Javascript object, created by a standard JavaScript object constructor.

Can we have two controllers in AngularJS?

Angular creates one $scope object for each controller. We also have a $rootScope accessible from every controllers.In case of multiple controllers AngularJS framework creates and pass a different $scope object to each controller so that data and methods of one controller not be accessed in another controller.


1 Answers

The easiest way to accomplish this is by using a service. For example:

app.factory( 'AuthService', function() {   var currentUser;    return {     login: function() { ... },     logout: function() { ... },     isLoggedIn: function() { ... },     currentUser: function() { return currentUser; }     ...   }; }); 

You can then reference this in any of your controllers. The following code watches for changes in a value from the service (by calling the function specified) and then syncs the changed values to the scope.

app.controller( 'MainCtrl', function( $scope, AuthService ) {   $scope.$watch( AuthService.isLoggedIn, function ( isLoggedIn ) {     $scope.isLoggedIn = isLoggedIn;     $scope.currentUser = AuthService.currentUser();   }); }); 

And then, of course, you can use that information however you see fit; e.g. in directives, in templates, etc. You can repeat this (customized to what you need to do) in your menu controllers, etc. It will all be updated automatically when you change the state on the service.

Anything more specific depends on your implementation.

Hope this helps!

like image 147
Josh David Miller Avatar answered Oct 06 '22 10:10

Josh David Miller