在下面的代码中,
<label>
<input type="checkbox" ng-model="showList">
Show unordered list
</label>
<ng-include src="getList()"></ng-include>
$scope.getList()
通过检查或取消选中在更改$scope.showList
时被调用,其中$scope.showList
用作,
app3.controller('gListCtrl', function($scope){
$scope.getList = function(){
return $scope.showList ? "ulgrocerylist.html" : "grocerylist.html";
};
});
为什么$scope.getList()
在$scope.showList
状态更改时被调用?
类似的代码,
<p>
<button ng-disabled="disableButton">Button</button>
</p>
<p>
<input type="checkbox"
ng-model="disableButton">DisableButton
</p>
对我来说很有意义,因为disableButton
状态正在发生变化,因此按钮由于双向绑定而被禁用或启用。
首先,你的问题有点不正确。$scope.getList()
函数不仅在状态更改时被调用,而且在每个摘要周期中被调用。让我解释一下。
因为框架绝对不知道getList
函数中的代码是什么。它不会静态地分析您的代码,因为它既困难又非常无辜。由于如何使用 AngularJS,您可以根据完全不同的控制器、服务、作用域等中的变量更改getList
的输出。因此,可能需要在每个摘要周期重新呈现此输出。AngularJS认识到这一点,因为您的模板中有函数调用,并在每个摘要上调用它以检查它是否需要交换模板。
请考虑以下应用程序结构:
<div ng-app="testTest">
<script type="text/ng-template" id="template.html">
<div>Hello world!</div>
</script>
<div ng-controller="templateViewer">
<div>
<div ng-include="content()"></div>
</div>
</div>
<div ng-controller="templateChanger">
<button ng-click="handleClick()">Show / hide content</button>
</div>
</div>
和这个代码来连接它:
var app = angular.module('testTest', []);
app.factory('template', function() {
return {
show: false
};
});
app.controller('templateChanger', function($scope, template) {
$scope.handleClick = function() {
// toggle showing of template
template.show = !template.show;
};
});
app.controller('templateViewer', function($scope, template) {
// if the result of this function is not re-evaluated on every digest cycle,
// Angular has no idea whether to show or hide the template.
$scope.content = function() {
return template.show ? 'template.html' : '';
};
});
因此,框架需要依赖于对绑定到 HTML 中模板的属性和函数的这种不断的重新评估。由于您使用的所有数据结构都是纯 javascript 对象,并且您没有明确告诉框架您的视图模型中的某些内容已更改(就像您在其他框架(如 Backbone 或 Ember )中的模型上调用set()
方法所做的那样) – angular 必须检查所有变量并重新运行所有可能改变视图外观的函数, ng-include
就是其中之一。
您可以使用观察程序或观察 showList 变量值更改的事件。