Chr*_*ris 33 javascript angularjs
我有一个简单的导航对象设置,列出导航项(以及它们是否应该出现在主导航中).事实上,当我尝试将ng-if与ng-repeat混合时,事情就会分崩离析,但是当我将ng-show与ng-repeat混合时,它工作正常(但我最终得到了一堆隐藏的元素,我不这样做想要附加到DOM).
<section class="nav">
<a ng-repeat="(key, item) in route.routes"
ng-href="{{key}}"
ng-show="item.nav"
>
{{item.label}}
</a>
</section>
Run Code Online (Sandbox Code Playgroud)
但以下不起作用(注意ng-show现在是ng-if):
<section class="nav">
<a ng-repeat="(key, item) in route.routes"
ng-href="{{key}}"
ng-if="item.nav"
>
{{item.label}}
</a>
</section>
Run Code Online (Sandbox Code Playgroud)
routes对象看起来像
routes: {
'/home': { label: 'Home', nav: true },
'/contact': { label: 'Contact', nav: false},
// etc
}
Run Code Online (Sandbox Code Playgroud)
我在尝试使用时收到以下错误ng-if:
错误:多个指令[ngIf,ngRepeat]要求进行翻译:
我想它试图告诉我,我不能说明现有两次的声明.我可以使用ng-if内部元素,但我想我仍然会得到一堆空的外部a标签.
Cuo*_* Vo 19
可能有更好的解决方案,但在阅读上面的回复后,您可以尝试制作自己的自定义过滤器:
angular.module('yourModule').filter('filterNavItems', function() {
return function(input) {
var inputArray = [];
for(var item in input) {
inputArray.push(input[item]);
}
return inputArray.filter(function(v) { return v.nav; });
};
});
Run Code Online (Sandbox Code Playgroud)
然后使用它:
<section class="nav">
<a ng-repeat="(key, item) in routes | filterNavItems"
ng-href="{{key}}">
{{item.label}}
</a>
</section>
Run Code Online (Sandbox Code Playgroud)
这是Plunker:http://plnkr.co/edit/srMbxK?p = preview