2014-07-22 42 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

相關問題