AngularJS - Shared state between controllers?

后端 未结 2 742
忘了有多久
忘了有多久 2021-01-11 16:11

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

2条回答
  •  一整个雨季
    2021-01-11 16:56

    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.

提交回复
热议问题