$ scope。$ watch在属性更新时不会触发

时间:2014-05-30 21:53:55

标签: javascript angularjs

以下是观察者声明:

$scope.$watch($scope.currentStep , function(newVal , oldVal){
    console.log('Watch: ' ,$scope.currentStep , newVal , oldVal);
});

这是唯一一个更改currentStep属性的代码,这些函数是在浏览器点击按钮时触发的:

$scope.next = function(valid , event){
    event.preventDefault();

    if(valid){
        $scope.error = false;

         $scope.validate();

        if($scope.currentStep < $scope.totalSteps && !$scope.error){
            $scope.previousStep = $scope.steps.indexOf(true);
            $scope.currentStep = $scope.steps.indexOf(true) + 1;

            $scope.steps[$scope.previousStep] = false;
            $scope.steps[$scope.currentStep] = true;                       
        }
    }
    else {
        $scope.error = true;
        $scope.errorText ="Please fix your mistakes";
    }
}

$scope.prev = function(){
    $scope.error = false;
    $scope.final = false;
    $scope.lastPush --;

    $scope.previousStep = $scope.steps.indexOf(true);
    $scope.currentStep = $scope.steps.indexOf(true) - 1;

    $scope.steps[$scope.previousStep] = false;
    $scope.steps[$scope.currentStep] = true;            
}

我无法理解的是,无论我做什么,手表只会触发变量的初始化。当currentStep更新时,手表会错过它。我已经尝试用watch来包含第三个参数来强制观察者通过相等而不是引用进行比较,但这并不能解决问题。我在这里缺少什么?

2 个答案:

答案 0 :(得分:4)

根据$rootScope.$watch文档,您的$watch表达式必须是StringFunction

以下任何一种都应该有效:

// String
$scope.$watch('currentStep', function(newVal, oldVal) {
    console.log('Watch: (current) %o (new) %o (old) %o', $scope.currentStep, newVal, oldVal);
});

// Function
$scope.$watch(function() {
    return $scope.currentStep;
}, function(newVal, oldVal) {
    console.log('Watch: (current) %o (new) %o (old) %o', $scope.currentStep, newVal, oldVal);
});

答案 1 :(得分:3)

$watch的第一个参数采用表达式或函数:

$scope.$watch('currentStep' , function(newVal , oldVal){
    console.log('Watch: ' ,$scope.currentStep , newVal , oldVal);
});

是的,您可以使用功能

$scope.$watch(function(){ return $scope.currentStep } , function(newVal , oldVal){
    console.log('Watch: ' ,$scope.currentStep , newVal , oldVal);
});

但这显然更冗长,更不可取。

$watch docs