Tuesday, June 30, 2015

Dynamic filter using AngularJS filter

In the post AngularJS filter, we saw on how to use filters to define a static filter in an array of elements, we can further enhance this by binding the filter text to a textbox control to create a dynamic filter.

In the following example a ng-repeat directive is used to display a list of employees, txtSearch is a textbox which is bound as the filter condition for the list, now as the user types some text in the textbox, the list will get filtered based on the text entered.
<html ng-app>
<head>
    <meta charset="utf-8" />
    <title>AngularJS - Basic</title>
    <script src="angular.min.js"></script>
        <script>
                function searchController($scope){
                       $scope.Reset = function() {
                                       $scope.txtSearch = '';
                             }
                }
    </script>
</head>
<body>
          <div ng-controller="searchController" ng-init="Employees=[
                                      {id:1,Name:'Tom'},
                                      {id:2,Name:'Harry'},
                                      {id:3,Name:'Peter'},
                                      {id:4,Name:'Thomas'},
                                      {id:5,Name:'Tiger'},
                                      {id:6,Name:'Topas'}]">
                    Search Text: <input type="text" ng-model="txtSearch"> 
                    <button ng-click="Reset()">Clear</button>
                    <ul>
                       <li ng-repeat="emp in Employees | filter:txtSearch">
                         {{ emp.id }} - {{ emp.Name }}<br/>
                       </li>
                   </ul>
          </div>
</body>
</html>

Output:




Search Flipkart Products:
Flipkart.com

No comments: