Introduction
In this article I will tell you how to use the $filter service in AngularJs.
The $filter service can be used to filter the data, it is declared along with the $scope service.
Here I will create a simple example on $filter that will help you understand how to use the $filter service.
Step 1
First of all you need to add an external Angular.js file to your application, "angular.min.js".
For this you can go to the AngularJS official site or can download my source code and then fetch it or you can click on this link to download it: ANGULARJS.
After downloading the external file you need to add this file to the Head section of your application.
<head runat="server">
<title></title>
<script src="angular.min.js"></script>
</head>
Step 2
Now after adding the external JS file, the first thing you need to do is to add ng-app in the <HTML> Tag otherwise your application will not run.
<html ng-app xmlns="http://www.w3.org/1999/xhtml">
Now I will create a simple application that will help you understand this directive.
First I will create a JavaScript function where $filter will be declared and some initial values will be passed.
<script>
function x($scope, $filter) {
$scope.cars = [
{ carId: 001, carName: 'Santro' },
{ carId: 002, carName: 'i10 Grand' },
{ carId: 003, carName: '120' },
{ carId: 004, carName: 'Verna' },
{ carId: 005, carName: 'City' }];
$scope.cars2 = $scope.cars;
$scope.$watch('search', function (val) {
$scope.cars = $filter('filter')($scope.cars2, val);
});
};
</script>
As I described earlier, $filter is a service declared as $scope is declared, you can see that I created a function "x" in which the $scope and $filter services are declared.
Now in this function a variable is declared named "cars", using this variable some initial values are passed in carId and carName.
At the end a filter is applied on these initial values.
Step 3
Now our work on JavaScript is completed and we can move towards the design part of this application.
Write this code in the body section:
<div ng-app>
<div ng-controller="x">
<input type="text" ng-model="search">
<table>
<tbody>
<tr ng-repeat="car in cars">
<td>{{car.carId}}</td>
<td>{{car.carName}}</td>
</tr>
</tbody>
</table>
</div>
</div>



Join the conversation! Your thoughts help the community grow.