Archive
Custom filters in AngularJS
In this post I am going to show you how easy it is to write custom filters in AngularJS and for the simplicity of the demo I am going to display a list of cron-jobs in a tabular data. Each job has details like the Id, action etc. and has a status which is represented in numbers like 0,1,2 etc. This may be suitable from a storage or system point of view but is not that user-friendly, so lets write a custom filter to transform numeric values into user-friendly status.
First we start with an AngularJS controller "CronJobsController" and it will be responsible for calling the cronjobs ASP.NET Web API.If the call is successful the returned data is assigned to $scope.jobs object so that we can bind the data to our view.
app.js
var app = angular.module('mainApp', []); app.controller('CronJobsController', function ($scope,$http) { $scope.jobs = []; $http({ method: 'GET', url: '/api/cronjobs' }) .then(function(response) { $scope.jobs = response.data; },function(reason) { $scope.error = reason.data; }); });
Next step is to wire up the "myApp" to the HTML page by using the ng-app directive.
CronJobs.html
<body ng-app="mainApp"> <!--Html omitted for brevity --> </body>
Now I am going to create the view by adding some table mark-up and use bootstrap to format the HTML table. For data binding I’m going to use the ng-repeat directive to enumerate through the jobs and bind the data to the table.
CronJobs.html(cont.)
<div class="row"> <!-- Jobs Controller Scope --> <div class="col-md-12" ng-controller="CronJobsController"> <table class="table table-striped"> <thead> <tr> <th>Id</th> <th>Correlation Id</th> <th>Action</th> <th>Created</th> <th>Status</th> </tr> </thead> <tbody> <tr ng-repeat="job in jobs"> <td>{{job.id}}</td> <td>{{job.correlationId}}</td> <td>{{job.action}}</td> <td>{{job.created | date:'dd-MM-yyyy'}}</td> <td>{{job.status}}</td> </tr> </tbody> </table> </div> <!-- End of Jobs Controller Scope --> </div>
Lets run the application and we can see that everything is working perfectly.
Now we are going to build our custom filter "status" which will return a user-friendly status based on the numeric value.
statusfilter.js
/// <reference path="app.js" /> app.filter('status', function() { return function(status) { switch(status) { case 0: return "Not Started"; case 1: return "In Progress"; case 2: return "Completed"; default: return "Unknown"; } } })
Nothing special here a simple switch case statement returning user-friendly text and all is left is to apply this filter to our model’s status property as shown in below code snippet.
<td>{{job.status | status}}</td>
And after applying the filter we can see the user-friendly status is displayed instead of the numbers.
It’s a very simple yet powerful feature and another reason to love AngularJS.