Blogger news

Blogger templates

Friday, July 18, 2014

Custom filter in AngularJS

If you are new to AngularJS I would prefer to go through my introduction blog on AngularJS before read this article

Writing your own filter is very easy: just register a new filter factory function with your module. The following convert a string to upper case (Obviously you can convert string directly to upper case directly using toUpperCase function in controller itself but this is just an example how can we write custom filter)

Step 1- Create module

var FilterModule = angular.module("FilterModule", []);

Step 2- Create filter factory method

FilterModule.filter('upper', function() {
    return function(input) {
        return input.toUpperCase();
    };

});

Where ‘FilterModule’ is the module we created in first step

Step 3 – Create Controller

FilterModule.controller("FilterController", function ($scope) {
    $scope.name = "Thunder-Cats";
});

In controller we created a property ‘name’ and assigned value ‘Thunder-Cats’

Step 4- Create View

<!DOCTYPE html>
<html ng-app="FilterModule">
<head>
    <title></title>
    <script src="Scripts/angular.min.js"></script>
    <script src="Controllers/TestController.js"></script>
</head>
<body ng-controller="FilterController">
    <div><input type="text" value="{{name|upper}}" /></div>
</body>
</html>

We  set our module and controller and we have created a textbox and set value element of textbox to value="{{name|upper}}". Here textbox value will set to ‘name’ property of our controller and it will call our filter ‘upper’ factory function.


Output: THUNDER-CATS

No comments:

Post a Comment