角度监视 - 更新函数范围外的变量

时间:2014-08-09 11:13:28

标签: javascript angularjs

开始使用angularjs这个问题令我感到困惑。

结果如何以及如何确保当watch函数第二次运行时(在init上),testValue被"更改"。

<div ng-controller="MyCtrl"></div>

和js:

var myApp = angular.module('myApp',[]); 
function MyCtrl ($scope) {
  var testValue = null;
  $scope.watchMe = null;        
  $scope.$watch('watchMe', function () {
    console.log('testValue is', testValue);        
    if(testValue !== null){`enter code here`
        console.log('i want to do something different the 2nd time this code runs - but i never get in here...');
    }
    testValue ="changed";
  });
};

然后有小提琴:jsfiddle example of the code

非常感谢

2 个答案:

答案 0 :(得分:0)

您尝试使用手表的方式不是很正确

watch用于对模型更改做出反应以触发一些进一步的操作

因此您需要将模型设置为监视表达式并听取它,以便在有任何更改时调用watch

<div ng-app="myApp" ng-controller="MyCtrl">
  <input type="text" ng-model="name" placeholder="Enter your name">
  <p>{{greeting}}</p>
</div>

和js:

var myApp = angular.module('myApp',[]); 
function MyCtrl($scope) {
  $scope.name = "";

  $scope.$watch("name", function(newValue, oldValue) {
    if ($scope.name.length > 0) {
      $scope.greeting = "Greetings " + $scope.name;
         console.log("change detected: " + newValue);
    }
  });
}

答案 1 :(得分:0)

事实证明问题不在手表中,而是在控制器中被调用两次。我不确定为什么会在the fiddle中执行此操作,但我添加了一个日志以明确这是问题。

因此要清除 - testValue保持为null,因为在监视函数运行后,控制器函数再次运行并覆盖var testValue。

这可能是由于很多事情 - 在我的情况下,我将控制器分配给一个元素,也可以在小提琴中看到。

<div ng-controller="MyCtrl"></div>
相关问题