我不明白为什么ng-repeat似乎在做不必要的工作。
我已经实现了一个小的导航菜单示例来显示我的意思。我创建了一个包含控制器(NavCtrl)的Angular模块,其中I:
我创建了一个JSFiddle我的例子。
我的问题是:为什么ng-repeat循环会被执行三次?请注意我的Javascript方法navClass
中的控制台日志记录行。当我在Chrome中运行它并只是加载HTML时,我得到以下输出:
evaluating route: home, against page: home testmod.js:29
evaluating route: home, against page: teams testmod.js:29
evaluating route: home, against page: events testmod.js:29
evaluating route: home, against page: venues testmod.js:29
evaluating route: home, against page: settings testmod.js:29
evaluating route: home, against page: home testmod.js:29
evaluating route: home, against page: teams testmod.js:29
evaluating route: home, against page: events testmod.js:29
evaluating route: home, against page: venues testmod.js:29
evaluating route: home, against page: settings testmod.js:29
evaluating route: home, against page: home testmod.js:29
evaluating route: home, against page: teams testmod.js:29
evaluating route: home, against page: events testmod.js:29
evaluating route: home, against page: venues testmod.js:29
evaluating route: home, against page: settings testmod.js:29
在我看来,ng-repeat循环运行了三次,在我的5项示例菜单列表中产生了15行输出,即使我的标记看起来只应该遍历项目一次:
<div>
<ul ng-controller="navCtrl">
<li ng-repeat="navLink in navLinks"> <a href='#/{{navLink.Title}}' ng-class="navClass('{{navLink.Title}}')">{{navLink.LinkText}}</a> </li>
</ul>
</div>
高度赞赏的解释或建设性批评!
答案 0 :(得分:0)
由于AngularJS 2路数据绑定,您会看到日志记录运行3次:$ apply()和$ digest()。 $ digest至少运行两次以检查是否有任何变化。肮脏的检查确实有其成本;(
更好的方法是使用函数表达式,我们可以使用ng-class:
<ul ng-controller="navCtrl">
<li ng-repeat="navLink in navLinks"> <a href='#/{{navLink.Title}}' ng-class="myVar" ng-click="myVar = 'active'">{{navLink.LinkText}} </a>
</li>
</ul>
希望这有帮助!