Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to use Filter in Angular JS

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 908
    Comment on it

    A filter is used to format the value of some expression when it is displayed to the user. It can be think as selecting the elements from an array in a particular format and returns a new array.

    It can be used by the following ways:

    In HTML Template Binding

    {{ filterExpression | filter : expression : comparator}}
    

    In JavaScript

    $filter('filter')(array, expression, comparator)
    

    Array : It is the array of source.

    Expression: Can be one of:

    String:All strings in the source array that match with this string will be returned.

    Object:An object can be used to filter specific properties on objects of the source array.
    For example {name:"S", phone:"2"} will return an array of items which have property name "S" and property phone containing "2".

    function(value, index):The function is called for each element of array. The final result is an array of those elements that is returned.

    Comparator: It is used to determine if the expected value (from the filter expression) and actual value (from the object in the array) is matching or not.

    It can be one of:

    function(actual, expected):It will give the two values that is object value and the predicate value to compare and return true if both values are equal.

    Example:

    HTML:

    <body ng-app="FilterApp">
      <div ng-controller="FilterCtrl">
        <form class="form-filter">
          <input ng-model="query-filter" type="text"
            placeholder="Filter by">
        </form>
        <ul ng-repeat="user in users | filter:query-filter | orderBy: 'name' ">
          <li>{{user.name}}</li>
        </ul>
      </div>
    </body>
    

    JavaScript:

    var app = angular.module("FilterApp", []);
    
    app.controller("FilterCtrl", function($scope) {
      $scope.users = [
        { name: "Chris",   age: 22 },
        { name: "Harry",   age: 52 },
        { name: "Martin",   age: 21 },
        { name: "Olex",   age: 34 },
        { name: "Luther", age: 26},
        { name: "Emmey",  age: 33 }
      ];
    
      $scope.filterFunction = function(element) {
        return element.name.match(/^Ma/) ? true : false;
      };
    
    });
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: