【问题标题】:$scope.$watch does not trigger when property updates$scope.$watch 在属性更新时不会触发
【发布时间】:2014-07-20 18:19:45
【问题描述】:

这是观察者声明:

$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 中包含第三个参数,以强制观察者通过相等而不是引用进行比较,但这并不能解决问题。我在这里错过了什么?

【问题讨论】:

  • 看来你的问题已经解决了。你介意接受答案吗?保证如果不是我的,我不会生气!

标签: javascript angularjs


【解决方案1】:

根据$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);
});

【讨论】:

    【解决方案2】:

    $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

    【讨论】:

      猜你喜欢
      • 2016-03-07
      • 1970-01-01
      • 2013-07-21
      • 1970-01-01
      • 1970-01-01
      • 2017-08-20
      • 2016-03-10
      • 2016-06-19
      • 1970-01-01
      相关资源
      最近更新 更多