Filters are used for formatting data displayed to the user on View.
They can be used in view templates, controllers or services.Angular comes with a collection of built-in filters, but it is easy to define your own as well.
Custom Filter: If you wan to some modification on the set of data OR on a specific situation you want to do some modifications/replace/manipulation go for custom filter.
For Example:
I have a set of data, on each element I want to do some modification while iterating the dataset.
{userId : "1234", userName:"Krishna Kumar Chourasiya","userEmail":"kchourasiya@gmail.com"}
I want to read above json and display on below format:
User Id: 1234
User Name: Krishna Kumar Chourasiya
User Email: kchourasiya@gmail.com
HTML:
<div ng-repeat="(key, dataSet) in dataSets">
<div>{{key | titleCase}} </div>
</div>
JS Code:
App.filter('titleCase', function() {
return function(input) {
var newStr = input.charAt(0).toUpperCase();
for (var i = 1; i < input.length; i++) {
var char = input[i];
if (char.match(/[A-Z]/)) {
newStr += ' ' + char;
}
else {
newStr += char;
}
}
return newStr;
};
No comments:
Post a Comment