AngularJS : How to watch service variables?

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

    Building on dtheodor's answer you could use something similar to the below to ensure that you don't forget to unregister the callback... Some may object to passing the $scope to a service though.

    factory('aService', function() {
      var observerCallbacks = [];
    
      /**
       * Registers a function that will be called when
       * any modifications are made.
       *
       * For convenience the callback is called immediately after registering
       * which can be prevented with `preventImmediate` param.
       *
       * Will also automatically unregister the callback upon scope destory.
       */
      this.registerObserver = function($scope, cb, preventImmediate){
        observerCallbacks.push(cb);
    
        if (preventImmediate !== true) {
          cb();
        }
    
        $scope.$on('$destroy', function () {
          observerCallbacks.remove(cb);
        });
      };
    
      function notifyObservers() {
        observerCallbacks.forEach(function (cb) {
          cb();
        });
      };
    
      this.foo = someNgResource.query().$then(function(){
        notifyObservers();
      });
    });
    

    Array.remove is an extension method which looks like this:

    /**
     * Removes the given item the current array.
     *
     * @param  {Object}  item   The item to remove.
     * @return {Boolean}        True if the item is removed.
     */
    Array.prototype.remove = function (item /*, thisp */) {
        var idx = this.indexOf(item);
    
        if (idx > -1) {
            this.splice(idx, 1);
    
            return true;
        }
        return false;
    };
    

提交回复
热议问题