AngularJS : How to watch service variables?

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

    ==UPDATED==

    Very simple now in $watch.

    Pen here.

    HTML:

    BarController

    Name is: {{ name }}

    {{ item.name }}

    JavaScript:

    var app = angular.module('app', []);
    
    app.factory('PostmanService', function() {
      var Postman = {};
      Postman.set = function(key, val) {
        Postman[key] = val;
      };
      Postman.get = function(key) {
        return Postman[key];
      };
      Postman.watch = function($scope, key, onChange) {
        return $scope.$watch(
          // This function returns the value being watched. It is called for each turn of the $digest loop
          function() {
            return Postman.get(key);
          },
          // This is the change listener, called when the value returned from the above function changes
          function(newValue, oldValue) {
            if (newValue !== oldValue) {
              // Only update if the value changed
              $scope[key] = newValue;
              // Run onChange if it is function
              if (angular.isFunction(onChange)) {
                onChange(newValue, oldValue);
              }
            }
          }
        );
      };
      return Postman;
    });
    
    app.controller('FooCtrl', ['$scope', 'PostmanService', function($scope, PostmanService) {
      $scope.setItems = function(items) {
        PostmanService.set('items', items);
      };
      $scope.setName = function(name) {
        PostmanService.set('name', name);
      };
    }]);
    
    app.controller('BarCtrl', ['$scope', 'PostmanService', function($scope, PostmanService) {
      $scope.items = [];
      $scope.name = '';
      PostmanService.watch($scope, 'items');
      PostmanService.watch($scope, 'name', function(newVal, oldVal) {
        alert('Hi, ' + newVal + '!');
      });
    }]);
    

提交回复
热议问题