Using Built-in Filters

AngularJS provides several types of filters that enable you to easily format strings, objects, and arrays in AngularJS templates. Table 5.1 lists the built-in filters provided with AngularJS.

Image
Image
Image

Table 5.1 Filters That Modify Expressions in AngularJS Templates

Listings 5.7 and 5.8 show how to implement some basic filters in AngularJS. Listing 5.7 implements a controller with JSONObj, word, and days properties. Listing 5.8 implements number, currency, date, json, limitTo, uppercase, and lowercase filters directly in expressions in the template. Figure 5.4 shows the output of these listings.

Listing 5.7 filters.js: Building a Scope That AngularJS Filters Can Use


01 angular.module('myApp', [])
02   .controller('myController', function($scope) {
03     $scope.currentDate = new Date();
04     $scope.JSONObj = { title: "myTitle" };
05     $scope.word="Supercalifragilisticexpialidocious";
06     $scope.days=['Monday', 'Tuesday', 'Wednesday',
07                  'Thursday', 'Friday'];
08   });


Listing 5.8 filters.html: An AngularJS Template That Implements Various Types of Filters to Modify Data Displayed in the Rendered View


01 <!doctype html>
02 <html ng-app="myApp">
03   <head>
04     <title>AngularJS Filters</title>
05   </head>
06   <body>
07     <div ng-controller="myController">
08       <h2>Basic Filters</h2>
09       Number: {{123.45678|number:3}}<br>
10       Currency: {{123.45678|currency:"$"}}<br>
11       Date: {{ currentDate | date:'yyyy-MM-dd HH:mm:ss Z'}}<br>
12       JSON: {{ JSONObj | json }}<br>
13       Limit Array: {{ days | limitTo:3 }}<br>
14       Limit String: {{ word | limitTo:9 }}<br>
15       Uppercase: {{ word | uppercase | limitTo:9 }}<br>
16       Lowercase: {{ word | lowercase | limitTo:9 }}
17     <script src="http://code.angularjs.org/1.3.0/angular.min.js"></script>
18     <script src="js/filters.js"></script>
19   </body>
20 </html>


Image

Figure 5.4 Using AngularJS filters to modify data before displaying it in the AngularJS view.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset