Ng-include被调用得太频繁了

ng-include is being called far too often

本文关键字:调用 Ng-include      更新时间:2023-09-26

我发现当我使用ng-include时,它被调用的次数太多了。

每次你点击一个Nothing按钮或改变视图,或在输入框中输入一些东西,getView得到运行几次。更改视图时最多可更改6次。基本上,做任何改变$scope的事情都会生成对getView的调用。

我已经创建了一个活塞来显示我所描述的行为:plnkr.co

这是正常的行为吗?有没有办法使它只运行一次?我担心我可能会因此而失去性能。

我的代码:

index . html

<body ng-app="includeExample">
  <div ng-controller="ExampleController">
    <div class="row">
      <input type="text" ng-model="unrelated">
    </div>
    <div class="row">
      <tabset>
        <tab heading="View 1">
          <ng-include src="getView('template1')"></ng-include>
        </tab>
        <tab heading="View 2">
          <ng-include src="getView('template2')"></ng-include>
        </tab>
      </tabset>
    </div>
  </div>
</body>

Script.js

 angular.module('includeExample', ['ngAnimate', 'ui.bootstrap'])
   .controller('ExampleController', ['$scope',
     function($scope) {
       $scope.getView = function(filename) {
         console.log("getView " + new Date());
         return filename + ".html";
       };
     }
   ]);

Template1.html

Content of template1.html
<button type="button" class="btn btn-primary" ng-click="">Nothing</button>

每次运行摘要时,Angular都会调用你的getView方法,以确保值没有改变。这是angular将模型和视图绑定在一起的"魔法"的一部分。如果您查看开发工具的network选项卡,您将看到,每次摘要运行时,浏览器实际上并没有检索模板。知道这就是摘要的实际工作方式后,您应该相应地开发代码,在而不是直接绑定到视图的方法中运行密集操作!

有关摘要本身的更多信息,请参阅:

  • http://angular-tips.com/blog/2013/08/watch-how-the-apply-runs-a-digest/
  • https://docs.angularjs.org/guide/scope(搜索"范围生命周期")
  • https://www.ng-book.com/p/The-Digest-Loop-and-apply/

希望有帮助!

是的,每次你做任何事情,angularJS都会经过getView()。一个好的第一次迭代是将它分配给一个json对象,而不是使用get方法。实际上,最好不要在html中使用任何get类型的方法。然后,如果你真的不希望它改变,你可以删除双向绑定(渲染值没有数据绑定)。