Creating custom filters
Writing your own filter is very easy: just register a new filter factory function with
your module. Internally, this uses the
filterProvider.
This factory function should return a new filter function which takes the input value
as the first argument. Any filter arguments are passed in as additional arguments to the filter
function.
The filter function should be a pure function, which
means that it should be stateless and idempotent. Angular relies on these properties and executes
the filter only when the inputs to the function change.
Note: Filter names must be valid angular
Expressions identifiers, such as uppercase or orderBy.
Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
your filters, then you can use capitalization (myappSubsectionFilterx) or underscores
(myapp_subsection_filterx).
The following sample filter reverses a text string. In addition, it conditionally makes the
text upper-case.
-----------------------
index.html
----------------------
<div ng-controller="MyController">
<input ng-model="greeting" type="text"><br>
No filter: {{greeting}}<br>
Reverse: {{greeting|reverse}}<br>
Reverse + uppercase: {{greeting|reverse:true}}<br>
</div>
---------------------
script.js
----------------------
angular.module('myReverseFilterApp', [])
.filter('reverse', function() {
return function(input, uppercase) {
input = input || '';
var out = "";
for (var i = 0; i < input.length; i++) {
out = input.charAt(i) + out;
}
// conditional based on optional argument
if (uppercase) {
out = out.toUpperCase();
}
return out;
};
})
.controller('MyController', ['$scope', function($scope) {
$scope.greeting = 'hello';
}]);
No comments:
Post a Comment