AngularJS:如果循环中的项目等于当前位置,则打印特定 class

AngularJS: if item in loop equals current location then print specific class

我有以下代码:

<ul ng-init="urls = ['/home', '/news', '/contactUs']">
<li ng-repeat="url in urls>
<a class="current-page" href="{{url}}">
{{url}}
</a>
</li>
</ul>

对于 ng-repeat 循环中的每个 <a> 标记,如果 {{url}} 等于 window.location.href.split('?')[0] 那么我想打印当前页 class对于那个 <a> 标签。否则,不应显示。 简单来说,我想要这样的东西:{{url || if(url == window.location.href.split('?')[0])}}

AngularJS 可以吗?那怎么办?

如果你有 ['example.com/home', 'example.com/news', 'example.com/contactUs'] 那么我建议:

<a ng-class="{ 'current-page': (window.location.host + window.location.pathname).indexOf(url) >= 0 }">{{url}}</a>

但是如果你有 ['/home', '/news', '/contactUs'] 那么这就足够了:

<a ng-class="{ 'current-page': window.location.pathname.indexOf(url) >= 0 }">{{url}}</a>

鉴于你的例子 urls 我认为这样更好,因为 href 也会包含该方案(例如 'https'),因此不会弹出任何匹配项。

如果更合适,您当然可以将 indexOf(...) 替换为完全匹配。

它利用了 ng-class 可以接受从潜在 类 ('current-page') 到求值后强制转换为布尔值的表达式的映射(例如 indexOf(...)表达式)。参见 these docs