简体   繁体   English

angularjs:未触发$ watch

[英]angularjs: $watch not triggered

trying to do something simple here. 尝试在这里做一些简单的事情。

In my controller: 在我的控制器中:

  $scope.testObject = { name : 'john' };

  $scope.$watch('$scope.testObject.name', function (e, n, v) {
      console.log('reached');
  });

In my view: 在我看来:

  <input type="text"  ng-model="testObject.name"/>

The textbox is bound to the testObject's name property and when the controller is loaded, the code goes into the $watch function. 文本框绑定到testObject的name属性,并且在加载控制器时,代码进入$ watch函数。

Now, if I edit the textbox value, the $watch function is never triggered. 现在,如果我编辑文本框值,则不会触发$ watch函数。 Why is that ? 这是为什么 ?

I've also tried setting the third argument of $watch to true, with no effects. 我也尝试将$ watch的第三个参数设置为true,没有任何效果。

Remove the $scope from your watch. 从手表中删除$ scope。 It should read as: 它应显示为:

$scope.$watch('testObject.name', function(e,n,v){
    console.log("reached");
});

Use this: 用这个:

$scope.$watch('testObject.name', function(e,n,v){
    console.log("reached");
});

You can also add other observer like this: 您还可以像这样添加其他观察者:

$scope.$watch('testObject.attr1 + testObject.attr2', function(e,n,v){
    console.log("reached");
});

or: 要么:

$scope.$watch('testObject', function(e,n,v){
    console.log("reached");
}, true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM