Same data in multiple views using AngularJS

后端 未结 2 1128
太阳男子
太阳男子 2021-02-04 17:58

Maybe there is someone who can help me a little bit. I have to share data between multiple views. Because it is a school project, I have to use AngularJS, but I am new to it and

2条回答
  •  遥遥无期
    2021-02-04 18:31

    Services are singletons, so when the service is injected the first time, the code in the factory gets called once. I'm assuming you have a routing table, since you are talking about multiple pages.

    If you define this

    angular.module('services', [])
    .factory('aService', function() {
      var shinyNewServiceInstance;
      //factory function body that constructs shinyNewServiceInstance
      shinyNewServiceInstance = shinyNewServiceInstance || {foo:1};
      return shinyNewServiceInstance;
    });
    

    Dependency inject it into your controllers (simplified):

    controller('ACtrl', ['aService', function(aService) {
      aService.foo += 1;
    }]);
    
    controller('BCtrl', ['aService', function(aService) {
      aService.foo += 1;
    }]);
    

    If you examine aService.foo each time you navigate between ACtrl & BCtrl, you will see that the value has been incremented. The logical reason is that the same shinyNewServiceInstance is in your hand, so you can set some properties in the hash from the first page & use it in the second page.

提交回复
热议问题