Wednesday 7 January 2015

Piping filter and order by with ng-repeat in AngularJS.



In the last few example as I have gone through how to generate html list / table using constant array value or importing json data, now in this example we will go through using filter and order by to enhance search capability without reloading the page. This can be done by piping filter where filter can use any constant string value or can bind to any user input to make filter dynamic, the search capability will be more dynamic when user type it's search key and list gets filtered. Same can be done with orderBy. orderBy will set data of table in order by the key mentioned. In this program I have set link to headers the data gets sorted for the column clicked.

Download angularjs api from http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js 
or you can also use this link in you script src.

<html ng-app="myApp">
<head>
<meta charset="utf-8">
<title>Angular.js example</title>

//Included the script 
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script>
myApp=angular.module('myApp',[]);
myApp.controller('myCtrl',function($scope) {
$scope.allinfo = [
{Name:'Jim',Age:22,Sex:'Male'},
{Name:'Jane',Age:23,Sex:'Female'},
{Name:'Alex',Age:21,Sex:'Male'},
{Name:'Paul',Age:19,Sex:'Male'},
{Name:'Britney',Age:23,Sex:'Female'}
];
$scope.reverse=true;
});
</script>
</head>
<body ng-controller="myCtrl">
Search : <input type=text ng-model="SearchField" />
<table border=1>
    <tr>
        <th><a href="" ng-click="sortField = 'Name'; reverse=!reverse">Name</a></th>
        <th><a href="" ng-click="sortField = 'Age'; reverse=!reverse">Age</a></th>
        <th><a href="" ng-click="sortField = 'Sex'; reverse=!reverse">Sex</a></th>
    </tr>
    <tr ng-repeat="perinfo in allinfo | filter:SearchField | orderBy:sortField:reverse">
        <td>{{perinfo.Name}}</td>
        <td>{{perinfo.Age}}</td>
        <td>{{perinfo.Sex}}</td>
    </tr>
</table>
</body>
</html>

Angular.js example Search :
Name Age Sex
{{perinfo.Name}} {{perinfo.Age}} {{perinfo.Sex}}

No comments: