Monday, August 14, 2017

filter filters in angular

Select a subset of elements from an array and return the result in a new array.
Syntax:
  {{ filter_expression | filter : expression : comparator : anyPropertyKey}}

expression The predicate to be used for selecting items from array.The final result is an array of those                          elements that the predicate returned true for.
Comparator : Defaults to false.
Example:

In JavaScript:
var myApp = angular.module('myApp', []);
myApp.controller('StdController', function($scope) {
  var StdDetails = [{
    StdName: "Mohit",
    StdClass: "MCA"
  }, {
    StdName: "Amit",
    StdClass: "BSC"
  }, {
    StdName: "Manoj",
    StdClass: "Xii"
  }];
  $scope.StdDetails = StdDetails;
  $scope.flt = function(element) {
    if ($scope.StdName1 == undefined || $scope.StdName1 == "") {
      return true;
    } else {
         var regExp = new RegExp("^" + $scope.StdName1, "gi");
      var val = element.StdName.match(regExp) ? true : false;
      return val;
    }
  };
});
In HTML:
<div ng-controller="StdController">
  <div><b>Filter in filters</b></div>
  <!-- Approch#1 -->
  <hr/> Exact match search:
  <input type="checkbox" ng-model="IsExactMatch" />
  <br/> Entire column search : &nbsp;
  <input type="textbox" value="" ng-model="stdname.$" placeholder="input value" />
  <br/>
  <br/> Student Name column search by HTML:
  <input type="textbox" ng-model="stdname.StdName" placeholder="input value" />
  <hr/>
  <table>
    <tr>
      <th>Student Name </th>
      <th>Class</th>
    </tr>
    <tr ng-repeat="std in StdDetails | filter:stdname:IsExactMatch">
      <td>{{std.StdName}} </td>
      <td>{{std.StdClass}}</td>
    </tr>
  </table>
  <!-- Approch#2 -->
  <hr/>
  <br/> Student Name column search by function:
  <input type="textbox" ng-model="StdName1" placeholder="input value" />
  <table>
    <tr>
      <th>Student Name </th>
      <th>Class</th>
    </tr>
    <tr ng-repeat="std in StdDetails | filter:flt">
      <td>{{std.StdName}} </td>
      <td>{{std.StdClass}}</td>
    </tr>
  </table>
</div>

I created a fiddle here with a demo:
https://jsfiddle.net/8qm45ard/

No comments:

Post a Comment