How to use ng-if with ng-repeat?

后端 未结 5 1021
北恋
北恋 2020-11-30 13:40

I have a simple nav object setup that lists the nav items (and whether they should appear in the primary nav or not). It seems though when I try to mix ng-if with ng-repeat,

相关标签:
5条回答
  • 2020-11-30 14:00

    I ran into this problem as well, and found a couple ways to solve it.

    The first thing I tried was to combine ng-if and ng-repeat into a custom directive. I'll push that up to github sometime soon, but it's kludgy.

    The simpler way to do it is to modify your route.routes collection (or create a placeholder collection)

    $scope.filteredRoutes = {};
    angular.forEach($scope.route.routes, function(item, key) {
        if (item.nav) { $scope.filteredRoutes[key] = item; }
    };
    

    and in your view

    ...
    <a  ng-repeat="(key, item) in filteredRoutes"
    ...
    

    If you need it to be dynamically updated, just set up watches, etc.

    0 讨论(0)
  • 2020-11-30 14:02

    How about this one-liner using $filter:

    $scope.filteredRoutes = $filter('filter')($scope.route.routes, function(route){
      return route.nav;
    });
    
    0 讨论(0)
  • 2020-11-30 14:08

    There's probably a better solution, but after reading the replies above, you can try making your own custom filter:

    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; });
      };
    });
    

    Then to use it:

    <section class="nav">
        <a  ng-repeat="(key, item) in routes | filterNavItems"
            ng-href="{{key}}">
                {{item.label}}
        </a>
    </section>
    

    Here's the Plunker: http://plnkr.co/edit/srMbxK?p=preview

    0 讨论(0)
  • 2020-11-30 14:18

    Instead of ng-if you should use a filter (http://docs.angularjs.org/api/ng.filter:filter) on you ng-repeat to exclude certain items from your list.

    0 讨论(0)
  • 2020-11-30 14:22

    You should use a filter in your ng-repeat instead of using ng-if.

    This should work:

    <section class="nav">
        <a  ng-repeat="(key, item) in route.routes | filter:item.nav"
            ng-href="{{key}}">
                {{item.label}}
        </a>
    </section>
    

    Warning: I haven't actually tested this code.

    0 讨论(0)
提交回复
热议问题