0

在下面的代码中,

        <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状态正在改变,所以按钮由于两种方式绑定而被禁用或启用。

4

2 回答 2

1

首先,你的问题有点不正确。该$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 对象,并且您没有明确告诉框架您的视图模型中的某些内容发生了变化(就像您set()在其他框架中调用模型上的方法一样,例如 Backbone 或 Ember) – angular 必须检查所有变量并重新运行所有可能改变视图外观的函数,这ng-include就是其中一种情况。

于 2016-03-13T03:04:44.017 回答
-1

您可以使用 watcher 或观察 showList 变量值变化的事件。

于 2016-03-13T02:06:20.987 回答