Roger Alsing Roger Alsing - 1 year ago 106
AngularJS Question

AngularJS - Shared state between controllers?

I know there are other similar questions on how to pass data between Angular controllers.

What I wonder is how to deal with this in a view..

Lets say I have a UserController for login, registration etc.
And an AppController for the actual app functionallity .

The UserController would be fairly easy, its sort of standalone from the rest.
But what if the app needs to know about stuff from the user controller?

Lets say the app view needs to hide/show stuff depending on if the user is logged in or not.
Or it could be if the user is male or female etc.

Should the app model keep its own copy of the user model state?
e.g. appModel.isLoggedIn , appModel.gender etc ?

feels a bit redundant, but at the same time more testable.

So what is the correct way to do this?

Answer Source

Short answer

Create a service, see Creating Services for details.

Long answer

Services are - per se - application-wide singletons, hence they are perfect for keeping state across views, controllers & co.:

app.factory('myService', [ function () {
  'use strict';
  return {
    // Your service implementation goes here ...

Once you have written and registered your service, you can require it in your controllers using AngularJS' dependency injection feature:

app.controller('myController', [ 'myService', '$scope',
  function (myService, $scope) {
  'use strict';
  // Your controller implementation goes here ...

Now, inside your controller you have the myService variable which contains the single instance of the service. There you can have a property isLoggedIn that represents whether your user is logged in or not.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download