angular ng-repeat with condition

前端 未结 4 1889
猫巷女王i
猫巷女王i 2020-12-09 12:07

How do you do something like this in angular with ng-repeat? I\'ll be using the example from the documentation which inits an array with 2 friends, what if I wanted to only

相关标签:
4条回答
  • 2020-12-09 12:08

    I used a filter in ng-repeat to:

    <div ng-repeat="product in products | filter:{ colour: by_colour }">
    
    0 讨论(0)
  • 2020-12-09 12:19

    Here is the working fiddle

       $scope.call = function(a){
    
        if (a.age > 26)
            return true;
        else
            return false;
    
    }
    
    0 讨论(0)
  • 2020-12-09 12:28

    you can use "ng-show="friend.age >=26" with the ng-repeat="friend in friends". it will only show the friends who's age is greater than and equal to 26.

    <body>
    <div ng-init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]">
          I have {{friends.length}} friends. They are:
         <ul>
             <li ng-repeat="friend in friends" ng-show="friend.age >=26">
               [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
            </li>
        </ul>
    </div>
    </body>
    
    0 讨论(0)
  • 2020-12-09 12:30

    Create a custom filter.

    HTML:

    <html ng-app="someApp">
    

    and

    <li ng-repeat="friend in friends | age">
    

    JS:

    var someApp=angular.module('someApp', []);
    
    someApp.filter('age', function() {
        return function(input, uppercase) {
            var out = [];
            for (var i = 0; i < input.length; i++) {
                if(input[i].age >= 26){
                    out.push(input[i]);
                }
            }
            return out;
        }
    });
    
    0 讨论(0)
提交回复
热议问题