Home / 2016 / June

Monthly Archives: June 2016

Filter using for AngularJS

Filters are used in conjunction with arrays of data and also outside of loops. If you’re looping through data and want to filter out specific things, you’re in the right place, you can also use Filters for filtering what a user types inside an “input” field for example. There are a few ways to use Filters, inside Controllers or as a defined method. Here’s the method usage, which you can use globally:

myApp.filter('reverse', function () {
    return function (input, uppercase) {
        var out = '';
        for (var i = 0; i < input.length; i++) {
            out = input.charAt(i) + out;
        }
        if (uppercase) {
            out = out.toUpperCase();
        }
        return out;
    }
});

// Controller included to supply data
myApp.controller('MainCtrl', ['$scope', function ($scope) {
    $scope.greeting = 'Rasel Khan';
}]);

DOM usage:

<div ng-app="myApp">
    <div ng-controller="MainCtrl">
        <p>No filter: {{ greeting }}</p>
        <p>Reverse: {{ greeting | reverse }}</p>
    </div>
</div>

Output:

No filter:  Rasel Khan
Reverse:  nahK lesaR