Javascript 为什么不是';我的AngularJS$scope.$watch是否在服务更改时触发?

Javascript 为什么不是';我的AngularJS$scope.$watch是否在服务更改时触发?,javascript,angularjs,Javascript,Angularjs,在我的控制器中,我有: var-timespanServiceFn timespanServiceFn = function() { return timespanService.getTimespan(); }; $scope.$watch(timespanServiceFn, $scope.updateVolume()); 我的$scope.updateVolume()函数只有一个console.log,这样我就知道我做到了 我的timespan服务也非常简单: myApp.serv

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

timespanServiceFn = function() {
  return timespanService.getTimespan();
};

$scope.$watch(timespanServiceFn, $scope.updateVolume());
我的
$scope.updateVolume()
函数只有一个
console.log
,这样我就知道我做到了

我的
timespan服务也非常简单:

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
没有被触发?

手表将两个函数作为参数。您必须将第二个参数作为参数传递,但您只是在那里调用了它:

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

只需将其更改为:

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