AngularJS : How to watch service variables?

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

    You can insert the service in $rootScope and watch:

    myApp.run(function($rootScope, aService){
        $rootScope.aService = aService;
        $rootScope.$watch('aService', function(){
            alert('Watch');
        }, true);
    });
    

    In your controller:

    myApp.controller('main', function($scope){
        $scope.aService.foo = 'change';
    });
    

    Other option is to use a external library like: https://github.com/melanke/Watch.JS

    Works with: IE 9+, FF 4+, SF 5+, WebKit, CH 7+, OP 12+, BESEN, Node.JS , Rhino 1.7+

    You can observe the changes of one, many or all object attributes.

    Example:

    var ex3 = {
        attr1: 0,
        attr2: "initial value of attr2",
        attr3: ["a", 3, null]
    };   
    watch(ex3, function(){
        alert("some attribute of ex3 changes!");
    });
    ex3.attr3.push("new value");​
    

提交回复
热议问题