将数组传递给$ watchGroup并在更改时更新数组

时间:2014-09-25 17:31:46

标签: javascript arrays angularjs data-binding watch

问题:

我想将一组变量传递给$ watchGroup并循环遍历数组以更新每个变量的值,但这似乎不起作用:

$scope.secondsElapsed = stopWatchService.secondsElapsed;
$scope.minutesElapsed = stopWatchService.minutesElapsed;
$scope.colon = stopWatchService.colon;

$scope.timers = ['stopWatchService.secondsElapsed', 'stopWatchService.minutesElapsed', 'stopWatchService.colon'];

$scope.$watchGroup([$scope.timers], function(newValues, oldValues, scope){
    if (newValues && newValues !== oldValues){
        for (var i=0; i<newValues.length; i++){
            scope.timers[i] = newValues[i];
        }
    }
});

目前我的工作如下:

$scope.$watchGroup(['stopWatchService.secondsElapsed', 'stopWatchService.minutesElapsed', 'stopWatchService.colon'], function(newValues, oldValues, scope){
    scope.secondsElapsed = newValues[0];
    scope.minutesElapsed = newValues[1];
    scope.colon = newValues[2];
});

有什么想法吗?

3 个答案:

答案 0 :(得分:0)

您检查过$watchCollection吗? https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope#$ watchCollection

答案 1 :(得分:0)

尝试检查$ watchGroup,我认为这正是你的问题,将数组作为第一个参数传递,对吧?

答案 2 :(得分:0)

不要将$scope.timers放入数组中,它已经是一个。

$scope.$watchGroup($scope.timers, ...)代替$scope.$watchGroup([$scope.timers], ...)