为什么 $scope.getList() 在 $scope.showList 的状态更改时被调用
Why $scope.getList() gets invoked on state change of $scope.showList?
在下面的代码中,
<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 变量值更改的事件。
- Angular:如何在状态更改时调用scope方法
- Angularjs从纯JS函数调用$scope.function
- Angular js - 异步调用 $scope.users 后不更新模态值
- 在AngularJs中,当我调用函数时无法获得$scope
- AngularJS Scope.on和Scope.emit在筛选器中的调用顺序
- 仅在focusout字段之后调用$scope.watch函数
- 如何调用$scope$apply()仅当它's还没有进行中
- 如何通过AngularJS中的一个调用在多个控制器($scope)中插入相同的数据
- 分析异步调用未更新AngularJS中的$scope变量
- 我正在使用 $scope.$apply 在 http 调用后更新对象数组.谁能告诉我正确的方法
- 无法在茉莉花测试中调用$scope.form.$submitted:未定义
- 对 angular.extend 的调用不会导致 $scope.$watch proc
- 为什么 $scope.getList() 在 $scope.showList 的状态更改时被调用
- 无法调用$scope上定义的函数
- $scope.$on('$routeChangeSuccess'..) 和在 scope 函数中调用方法
- 角度$scope首先设置值而不是服务,然后第二个函数调用一切正常
- 尝试将数据数组设置为从视图调用函数后$scope
- 从 AngularJS 中$scope上定义的另一个函数调用$scope上定义的函数
- Scope.watch 在指令中调用在开头 angularjs
- Angular $http调用不绑定成功$scope.data