问题描述
我试图让AngularJs上取决于活动路由一个导航部分采用了有效
类。我的解决办法工作正常,但我注意到一个奇怪的行为 - 低于更多。现在,这里的活动类是如何在HTML设置:
I was attempting to get AngularJs to apply an active
class on a nav section depending upon the active route. My solution works fine but I noticed a curious behaviour -- more on that below. For now, here's how the active class is set in the HTML:
<ul class="menu" ng-controller="ControllerHeader">
<li><a ng-class="{ active: isActive('/foo') }" href="#/foo">foo</a></li>
<li><a ng-class="{ active: isActive('/bar') }" href="#/bar">bar</a></li>
<li><a ng-class="{ active: isActive('/baz') }" href="#/baz">baz</a></li>
</ul>
ControllerHeader
和 isActive
定义给出:
var app = angular.module('app', [ ]);
app.controller( 'ControllerHeader', ['$scope', '$location',
function ($scope, $location) {
$scope.isActive = function (location) {
// multiple logging occurs: exactly 3*3 times
console.log(location, $location.path());
return location === $location.path();
};
}
] );
我注意到的问题是 isActive
上面被称为第3 * 3次!可能有人请解释一下为什么?我怎样才能修复它,这样它被称为曾经每个项目只?
The issue I've noticed is that isActive
above is called 3 * 3 times! Could someone please explain why? How can I fix it that such that it is called once per item only?
推荐答案
如果您使用的是角1.3+,你可以使用:
运营商只能评估前pression一次:
If you are using Angular 1.3+, you can use the ::
operator to only evaluate the expression once:
<ul class="menu" ng-controller="ControllerHeader">
<li><a ng-class="::{ active: isActive('/foo') }" href="#/foo">foo</a></li>
<li><a ng-class="::{ active: isActive('/bar') }" href="#/bar">bar</a></li>
<li><a ng-class="::{ active: isActive('/baz') }" href="#/baz">baz</a></li>
</ul>
如果您正在使用的角度是旧版本,你可以使用一个第三方库,如
If you are using an older version of Angular, you can use a third party library such as bindonce
至于为什么发生这种情况不具有约束力一次,实际上它是由许多其他问题所覆盖。如果您希望类视角范围内动态设置,角的需求的执行,检查它的价值的功能。这就是所谓的摘要周期中执行观察家,而这往往是做。
As for why this is happening without binding once, indeed it is covered by many other questions. If you want the class to be dynamically set depending on angular context, Angular need to execute the function to check its value. That is called executing the watchers during a digest cycle, and this is done often.
这篇关于控制器功能被多次调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!