Monday, April 14, 2014

built in filters in angularjs


The initial setup:
index.html
  1. <div ng-app="myApp">
  2. <div ng-controller="AvengersCtrl">
  3. <input type="text" ng-model="search.$">
  4. <table>
  5. <tr ng-repeat="actor in avengers cast | filter:search">
  6. <td>{{ actor.name }}</td>
  7. <td>{{ actor.character }}</td>
  8. </tr>
  9. </table>
  10. </div>
  11. </div>
main.js
  1. var myApp = angular.module('myApp', []);
  2. myApp.factory('Avengers', function () {
  3. var Avengers = {};
  4. Avengers.cast = [
  5. {
  6. name: ...,
  7. character: ...
  8. },
  9. ...
  10. ];
  11. return Avengers;
  12. });
orderBy
index.html
  1. <tr ng-repeat="actor in avengers cast | orderBy:'name'">
This filter sorts the collection by the name field. -name will reverse the order.
limitTo
index.html
  1. <tr ng-repeat="actor in avengers cast | limitTo:5">
This filter returns only the first 5 results. -5 will return only the last 5 results.
The pipe operator allows filters to be stacked and evaluated sequentially on the results of the previous collection filter.
index.html
  1. <tr ng-repeat="actor in avengers cast | filter:search | orderBy:'name' | limitTo: 5 ">
This filter will filter the entire collection against the search model, order the matched results by the name attribute, and limit the result set to 5 entries.
Model data can be treated as a filterable collection as well:
index.html
  1. <tr ng-repeat="actor in avengers cast | filter:search">
  2. <td>{{ actor.name | lowercase }}</td>
  3. <td>{{ actor.character | uppercase }}</td>
  4. </tr>

No comments:

Post a Comment