javascript - $watch 不会触发带有美元 ($) 的变量

标签 javascript angularjs angularjs-scope angularjs-watch

我有一个物体的 watch 。当对象的属性更改时,监视会触发,除非属性名称以美元 ($) 开头。

考虑这段代码:

$scope.data = {};

$scope.$watch('data', function (newValue, oldValue) {
        console.log('fired', newValue);
    }, true);

和 html:

<div>
this will fire the event
<input type="text" ng-model="data.x" />
</div>
<div>
this won't
<input type="text" ng-model="data.$" />
</div>

你可以在这个 fiddle 中亲眼看到它: https://jsfiddle.net/gtrwzsn1/179/

这对我来说非常重要,因为我必须使用带有 $ 的属性名称来进行过滤。

最佳答案

AngularJs 有“$watchCollection”函数作为观察集合(即数组或对象)中变化的方法。

$scope.$watchCollection('data', function (newValue, oldValue) {
  console.log('fired', newValue);
});

如果您想观看一个物体,请尝试上面的代码片段。希望这会有所帮助。

关于javascript - $watch 不会触发带有美元 ($) 的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44010230/

相关文章:

javascript - Angular ng-if 用于检查空字符串不起作用

javascript - 突出显示字符串中的多个子字符串——javascript/jquery

javascript - 如何解释通过ajax发送的javascript代码?

javascript - 使用 CSR 对 sharepoint 2013 上的列表进行条件格式化

angularjs - 使用 Angular2 和 TypeScript 将 http 功能移动到它自己的服务中

javascript - 从 AngularJS 外部触发更新/刷新

javascript - AngularJS:让元素跟随光标

jquery - Angular.js - 将 $scope 传递到 jQuery 函数

angularjs - 仅在定义 $scope.myVar 后渲染 AngularJS 指令

javascript - Python/Selenium - 努力点击导航栏中的按钮