Aki
Aki

Reputation: 743

AngularJS - Broadcasting across controllers

Am trying a scenario where i Login, and, on success, want to store that LoginID and pass it to all other controllers for navigation/user management. Similar to a global variable set up, store once use everywhere concept.

Been using angularjs shared Services technique but its not picking the braodcaster LoginID in other controllers.

High level details:

1) Login HTML calls Login Controller from where i call back end server for user authentication 2) On success, broadcasted LoginID via shared service 3) from Login HTML, page navigates to OrderMenu Html and calls OrderMenu controller where am trying to fetch the User id which was broadcasted via the shared service. 4) but in the Order Menu controller the UserID shown is the initialized value i.e looks like app.factory is being called again and initializing the Broadcasted value.

I want to stop the reloading of app.factory. Looks like am missing something here.Any thoughts would be really helpful here.

Upvotes: 1

Views: 571

Answers (1)

Tosh
Tosh

Reputation: 36030

Here is a quick implemention example of what you described. And it seems to be working.

http://plnkr.co/edit/SPAB4W

My service is defined as follows:

app.factory('UserAuth', function() {
  return {
    userId: 'unknown',
    authenticate: function( name ) {
      // do server side authentication here...
      this.userId = 'authenticatedUserId_Of_' + name;
    }
  };
});

In this example, when second controller (OrderCtrl) is getting called, UserAuth.userId does not get re-initialized and keeps the obtained userId of what authentication gives.

You may want to share your code.

Upvotes: 1

Related Questions