Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular ng-repeat with condition

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 do a repeat for all friends that are 26 and older?

    <!doctype html>
<html ng-app>
<head>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
</head>
<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">
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
</li>
</ul>
</div>
</body>
</html>
like image 911
J.Pip Avatar asked Aug 05 '13 10:08

J.Pip


1 Answers

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;
    }
});
like image 59
AlwaysALearner Avatar answered Sep 28 '22 03:09

AlwaysALearner