Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an array of objects in scope, which I'm looping over with ng-repeat. I want to filter out some elements based on their values, but it seems like ng-if is completely ignored.

I've set up this simple plunk to illustrate: http://plnkr.co/edit/Aj0hpZQTfnkQ6BYG8DRb.
Here's the controller:

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';

  $scope.events = [
    {key: "ClassName", value: "exception", age:12},
    {key: "Message", value: "oops", age: 25},
    {key: "Stack", value: null, age: 35}
    ]
});

And the HTML template:

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js" data-semver="1.0.8"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    <ul>
      <li ng-repeat="event in events" ng-if="event.age > 20">
        [{{$index + 1}}] {{event.key}}: {{event.value}} - {{event.age}}
      </li>
    </ul>
  </body>

</html>

The ng-if directive is supposed to filter out the first element of the array, bit it is displayed anyway. What have I missed that ignores the ng-if?

share|improve this question
 
"The ng-if directive is supposed to filter", no its not, it suppose to decide whether the whole element will be rendered or not, voted for CD.. –  bresleveloper Nov 12 at 8:50
add comment

2 Answers

up vote 3 down vote accepted

I suppose the right way would be using a filter, for example:

<li ng-repeat="event in events | filter:greaterThan">

Working example: http://plnkr.co/edit/Qy3BVEogEgGivtqel73b?p=preview

share|improve this answer
 
I didn't know that function call syntax. Thx! –  Antoine Nov 12 at 8:55
add comment

I think what you want is an actual filter.

Filters can be applied on expressions (like the repeat) and will return a list containing only items that fulfills the criteria of the filter. So in this case I think you would do.

  <li ng-repeat="event in events | maxAge:20">
    ...
  </li>

Note that maxAge is not one of the default filters (you can find them to the left in the here), you would have to create one on your own unless you can fit it into the existing ones. But creating filters is really easy, they are just functions that take an input, do whatever logic they feel like and then return the new values.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.