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?
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.
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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With