我来自Knockout,我想了解Angular如何更新范围。我有点困惑,为什么在范围上定义的函数(例如$scope.doStuff = function()
)在每个范围刷新上都被执行。为什么AngularJS在每个摘要循环上执行函数?
Plnkr链接:http://plnkr.co/edit/YnvOELGkRbHOovAWPIpF?p=preview
例如:
HTML
<div ng-controller="one">
<input type="text" ng-model="a">
{{b()}}
</div>
JS
angular.module('test', [])
.controller('one', ['$scope', function ($scope) {
$scope.a = 'one';
$scope.b = function() {
console.log('b has executed');
}
}])
所以每当一个事件发生在$scope.a
的输入表单字段中,函数$scope.b
被执行。为什么会发生?这个函数没有依赖关系,它总是令人耳目一新,效率不高。
如果我在同一结构中添加其他控制器,就像这样:
HTML
<div ng-controller="one">
<input type="text" ng-model="a">
{{b()}}
</div>
<div ng-controller="two">
<input type="text" ng-model="x">
{{y()}}
</div>
JS
angular.module('test', [])
.controller('one', ['$scope', function ($scope) {
$scope.a = 'one';
$scope.b = function() {
console.log('b has executed');
}
}])
.controller('two', ['$scope', function ($scope) {
$scope.x = 'two';
$scope.y = function() {
console.log('y has executed');
}
}])
我每次在控制器one
更新$scope.a
输出是:
b has executed
y has executed
为什么控制器two
执行$scope.y
?我想创建一个新的控制器创建一个新的子范围。是否因为子范围链接到父范围?
更有趣的是,如果我更新控制器two
$scope.x
那么输出是:
b has executed
y has executed
b has executed <-- a second time... what?
为什么功能$scope.b
得到执行第二次?
那么为什么Angular中的函数会在每个范围刷新上执行?
角度必须确保没有改变视图,因此它执行你在视图内使用的所有函数,并且检查视图内是否使用了所有变量 – Grundy
因此,如果我有一个包含1000个项目的'ng-repeat',并且每个人都有一个'ng-show =“函数()”'这意味着每次更新文本字段时,Angular将执行该函数1000次?这似乎是糟糕的表现明智的。 – Andrew
所以不要使用它1000个项目:-) – Grundy