Filtering a List of DOM Nodes

Problem

You wish to filter a ul list of names.

Solution

As well as with strings as input, Angular’s filters also work with arrays.

<body ng-app="MyApp">
  <ul ng-init="names = ['Peter', 'Anton', 'John']">
    <li ng-repeat="name in names | exclude:'Peter' ">
      <span>{{name}}</span>
    </li>
  </ul>
</body>
var app = angular.module("MyApp", []);

app.filter("exclude", function() {
  return function(input, exclude) {
    var result = [];
    for (var i=0; i<input.length; i++) {
      if (input[i] !== exclude) {
        result.push(input[i]);
      }
    }

    return result;
  };
});

We pass Peter as the single param to the exclude filter, which will render all names except Peter.

You can find the complete example on github.

Discussion

The filter implementation loops through all names and creates a result array excluding ‘Peter’. Note that the actual syntax of the filter function didn’t change at all from our previous example with the String input.