为什么不是我的AngularJS $作用域?$watch在服务变更时被触发

Why isn't my AngularJS $scope.$watch being triggered on service changes?

本文关键字:服务 watch 我的 AngularJS 作用域 为什么不      更新时间:2023-09-26

在我的控制器中,我有:var timespanServiceFn;

timespanServiceFn = function() {
  return timespanService.getTimespan();
};
$scope.$watch(timespanServiceFn, $scope.updateVolume());

我的$scope.updateVolume()函数只有一个console.log所以我知道我到达了那里

我的timespanService也超级简单:

myApp.service('timespanService', [
  '$http', '$q', function($http, $q) {
    var currentTimespan;
    currentTimespan = '3M';
    this.getTimespan = function() {
      return currentTimespan;
    };
    this.setTimespan = function(timespan) {
      console.log('setting timespan to', timespan);
      return currentTimespan = timespan;
    };
  }
]);

那么为什么当我改变时间跨度时,$watch没有被触发?

watch接受两个函数作为参数。你必须将第二个参数作为参数传递但是你刚刚调用了它:

$scope.$watch(timespanServiceFn, $scope.updateVolume());

因此,$scope.updateVolume()的返回语句将传递给$watch函数,而不是函数定义本身。

改成:

$scope.$watch(timespanServiceFn, $scope.updateVolume);
<<p> 看到演示/strong>