16.07.2017 Views

AngularJS Essentials

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 3<br />

Let's change our application by moving the date filter, which we used to display the<br />

date and hour separated in the view, to our controller:<br />

controllers.js<br />

parking.controller("parkingCtrl", function ($scope, $filter) {<br />

$scope.appTitle = $filter("uppercase")("[Packt] Parking");<br />

});<br />

This approach is often used when we need to transform the data before it reaches the<br />

view, sometimes even using it to the algorithms logic.<br />

Creating filters<br />

<strong>AngularJS</strong> already comes with a bunch of useful and interesting built-in filters,<br />

but even then, we'll certainly need to create our own filters in order to fulfill<br />

specific requirements.<br />

To create a new filter, you just need to register it to the application's module,<br />

returning the filter function. This function takes the inputted value as the first<br />

parameter and other additional arguments if necessary.<br />

Now, our application has a new requirement that can be developed through the<br />

creation of a customized filter.<br />

This requirement involves formatting the car's plate by introducing a separator after<br />

the third character. To achieve this, we are going to create a filter called plate. It will<br />

receive a plate and will return it after formatting it, after following the rules:<br />

filters.js<br />

parking.filter("plate", function() {<br />

return function(input) {<br />

var firstPart = input.substring(0,3);<br />

var secondPart = input.substring(3);<br />

return firstPart + " - " + secondPart;<br />

};<br />

});<br />

With this filter, the 6MBV006 plate is displayed as 6MB - V006.<br />

[ 61 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!