【发布时间】:2014-01-21 14:06:30
【问题描述】:
所以我对范围 A 有一个监视。为什么当同级范围 B 上的局部变量发生变化时 AngularJS 会评估它?范围A的数据模型没有改变。
这是一个最小的例子:
- 范围 A 上有一个自定义手表。
- 输入元素绑定到作用域 B 的
text变量。 - 请注意,
text未显示,因为它在范围 A 中不可见。
控制器:
function Ctrl1($scope) {
console.log($scope); // first scope
// my custom watch expression
var count = 0;
$scope.$watch(function() {
count++;
console.log("call count: " + count);
}, function() {
// the listener does nothing
// I'm just interested in when the watch expression is called
});
}
function Ctrl2($scope) {
console.log($scope); // second scope
}
HTML:
<div ng-app>
<div ng-controller="Ctrl1">
{{text}}
</div>
<div ng-controller="Ctrl2">
<input type="text" ng-model="text"></input>
</div>
</div>
(请随时在此处尝试此代码:http://jsfiddle.net/s3Wz5/4/)
如果您在输入元素(范围 B)中键入一些文本,则会评估范围 A 的自定义监视。为什么是这样?为什么 AngularJS 不知道作用域 A 的数据模型没有任何变化?
更新:一些说明:
我不想看text。这是一个与性能相关的问题,想知道为什么即使无法从其他范围读取 text 也会评估手表!
【问题讨论】:
标签: performance angularjs scope watch