AngularJS : How to watch service variables?

后端 未结 21 1645
盖世英雄少女心
盖世英雄少女心 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:40

    A wee bit ugly, but I've added registration of scope variables to my service for a toggle:

    myApp.service('myService', function() {
        var self = this;
        self.value = false;
        self.c2 = function(){};
        self.callback = function(){
            self.value = !self.value; 
           self.c2();
        };
    
        self.on = function(){
            return self.value;
        };
    
        self.register = function(obj, key){ 
            self.c2 = function(){
                obj[key] = self.value; 
                obj.$apply();
            } 
        };
    
        return this;
    });
    

    And then in the controller:

    function MyCtrl($scope, myService) {
        $scope.name = 'Superhero';
        $scope.myVar = false;
        myService.register($scope, 'myVar');
    }
    

提交回复
热议问题