13

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>

4 Answers 4

25

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;
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

thx, I found it allready it's indeed a filter :) I'm still learning angular.js and tbh it's a pretty big framework with a lot of bells and whistles to which I'm not accustomed yet :)
I too am going through the same road. Its just that I happened to know the answer on this occasion :D
15

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>

1 Comment

This works, but could cause a lot of unneeded markup, especially if you want to show all other age groups the same way.
7

Here is the working fiddle

   $scope.call = function(a){

    if (a.age > 26)
        return true;
    else
        return false;

}

2 Comments

I like the filter idea better... this is strange.
For me this is good, as you don't need to add the filter at app level, this will keep the filter function at controller scope.
4

I used a filter in ng-repeat to:

<div ng-repeat="product in products | filter:{ colour: by_colour }">

3 Comments

<div ng-repeat="product in products | filter:{ colour: by_colour }">
You should edit you answer instead of leaving a comment.
@Ivan I guess OP didn't understand how to format code, and the HTML was not showing. I fixed it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.