Using a filter in a controller

In the preceding section, we discussed how to create custom filters and implement them in the DOM. In this section, we will talk about how to use our custom filter inside a controller. In order to use a filter inside the controller, we need to inject the $filter dependency into the controller. This way, we will have access to both AngularJS's built-in filters and custom filters. The following code shows how to use a filter inside a controller:

var app = angular.module('myApp', []); 

<!--   Custom Filter  -- >
app.filter("ckeckCurrentYear", function () {

    return function (input) {

        var currentYear = new Date().getFullYear();

        //var modelYear = input.model;

        if (input == currentYear) {

            return input + ' ' + 'u2713';

        }
        else
        {
            return input +' '+'u2718';
        }
    };
});

<!--   Controller  -- >
app.controller("ctrlUsingFilterInController", function ($scope, $filter) {
    $scope.cars = [
      { name: "Honda", model: 2014 },
      { name: "Toyota", model: 2015 },
      { name: "Mercedes", model: 2013 },
      { name: "Ford", model: 2016 },
      { name: "BMW", model: 2014 },
      { name: "Porsche", model: 2015 }
    ];

    $scope.carList = [];

    angular.forEach($scope.cars, function (value, key) {

        var carName = value.name;

        var carYear = $filter('ckeckCurrentYear')(value.model);

        $scope.carList.push({ name: carName, model: carYear });
    });
});

We can render the HTML elements as follows:

<div ng-app="myApp" ng-controller="ctrlUsingFilterInController">

<ul ng-repeat="car in carList | orderBy: 'name'">

<li>{{car.name}} - {{car.model}}</li>

</ul>
</div>

The following screenshot shows the output of the preceding code:

Using a filter in a controller

In the preceding code, we injected a $filter'app.controller("ctrlUsingFilterInController", function ($scope, $filter)' into the controller in order to use both AngularJS built-in and custom filters. We looped through the $scope.cars object and applied the filter on the $filter('ckeckCurrentYear')(value.model) model. We then saved the new values in another array, $scope.carList. In the view, we called the new array using the ng-repeat directive and displayed the result in the DOM. It is noticeable that we did not apply our custom filter in the DOM, but instead inside the controller.

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

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