2014-07-22 95 views
0

在我的控制器中,我有: 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不会被触发?

回答

1

手表有两个函数作为参数。你必须通过第二个参数作为参数,但你只是把它叫做有:

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

所以$scope.updateVolume() return语句将被传递到$watch函数而不是函数定义本身。

只是将其更改为:

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

See demo

相关问题