AngularJS : How to watch service variables?

后端 未结 21 1807
盖世英雄少女心
盖世英雄少女心 2020-11-22 09:12

I have a service, say:

factory(\'aService\', [\'$rootScope\', \'$resource\', function ($rootScope, $resource) {
  var service = {
    foo: []
  };

  return          


        
21条回答
  •  时光说笑
    2020-11-22 09:26

    // service: (nothing special here)

    myApp.service('myService', function() {
      return { someVariable:'abc123' };
    });
    

    // ctrl:

    myApp.controller('MyCtrl', function($scope, myService) {
    
      $scope.someVariable = myService.someVariable;
    
      // watch the service and update this ctrl...
      $scope.$watch(function(){
        return myService.someVariable;
      }, function(newValue){
        $scope.someVariable = newValue;
      });
    });
    

提交回复
热议问题