Web Programming TutorialsLearn About Filters in AngularJS

Learn About Filters in AngularJS

Angular-filters

In this lesson, we’re going to learn about Angular filters. Filters are added to expressions or directives by a ‘|’ sign followed by the filter’s name. Angular filters serve to perform a variety of effects on data – some (such as the currency, date, JSON and number filters) transform the value of an element from one format into another; some change the appearance of data (such as the lowercase and uppercase filters, which transform a string from uppercase to lowercase and vice versa), and some (such as filter, limitTo and orderBy) selectively change the displayed order or size of a collection (array or string), depending on our specifications/criteria.

1) Let’s start with the simplest example of converting a string element from uppercase to lowercase using filters:

<body>
<div ng-app='Napp' ng-controller='nCtrl'>
<h3> I live in {{ city | lowercase }}, {{ state | lowercase }} </h3>
</div>

<script>
angular.module('Napp', []).controller('nCtrl', function($scope) {
    $scope.city = 'Seattle',
    $scope.state = 'Washington'
});
</script>

In the above example, we’ve used the lowercase filter inside an expression to transform the city and state strings to be all in lowercase format.

2) In the following example, we are going to move on to using a filter to selectively change the displayed array:

<div ng-app='filter_app' ng-controller='fCtrl'>
<h2>Enter string to filter by:</h2>
<p><input type='text' ng-model='check'></p>
<ul>
  <li ng-repeat='x in names | filter:check'>
    {{ x.last }}, {{x.first}}
  </li>
</ul>
</div>

<script>
angular.module('filter_app', []).controller('fCtrl', function($scope) {
    $scope.names = [
        {first:'carol', last:'smith'},
        {first:'Jayne', last:'roberts'},
        {first:'joe', last:'mckay'},
      {first:'tom', last:'carrol'},
      {first:'kevin', last:'mcdonnell'},
      {first:'stephen', last:'cohen'},
    ];
});
</script>

<h3>The above list includes only names containing the entered string.</h3>

Explanation: The ‘names’ attribute of our $scope object is an array of objects, each containing two key-value pairs of strings. In order to allow the array display to be filtered according to the user’s preference, we used the ng-model directive to bind the data the user enters in the input field to the filter, as an expression in the filter. Thus, when we iterate over the array using ng-repeat, the filter displays only selected elements from the array. More accurately, it only allows array names (full names) containing the string the user has entered to be displayed.

3) We can also create our own custom filters. For that we’ll need to create a new factory function for the filter and register it with our application. Example:

<body>
<ul ng-app='newApp' ng-controller='ctrl'>
    <li ng-repeat="x in names">
         {{x | custom_filter}}
   </li>
</ul>

<script>
var app = angular.module('newApp', []);
app.filter('custom_filter', function() {
    return function(x) {
        var i, word = "";
        x = x.split("")
        for (i = 0; i < x.length; i++) {
	            if (i == 0){
	               x[i] = x[i].toUpperCase();
                    }
                    word += x[i];
        }
        return word;
    };
});
app.controller('ctrl', function($scope) {
    $scope.names = ['donny', 'cindy', 'rafael', 'david', 'aidan'];
});
</script>
<p>We titled our new filter custom_filter. Its function is to chance the case to uppercase of the first letter of every string in an array of strings.</p>
</body>

Explanation: We’ve created a new app and a new filter(custom_filter) for that app. To register the new filter with the app, we use the formula app.filter(FilterName, function() {});

Inside the filter factory function, we wrote a function that takes the value of each array item (referenced by x) as a parameter and converts each array item into an array of letters with the splice() method.

We then iterate over that array and convert the current letter to an uppercase if it’s the first letter. We reassembled the array into a one-word string then and returned the result.
In the HTML, we then used ng-repeat to iterate over the array items and apply the custom filter to each and every one of them.

Summary,
In this article we’ve seen diverse uses for Angular filters. Some transform the value of an element from one format into another; some change the appearance of data and some  selectively change the displayed order or size of a collection (array or string), depending on our specifications/criteria. Hope you have liked this tutorial. I will be back with some more tutorials on AngularJS till then keep learning.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -