We can use AngularJS filter to format the data.
AngularJS has several built-in filters and provides an easy way to create our filters.
We call filters in HTML with the |
(pipe) character inside {{ }}
.
To capitalize our string we can use buildin filter.
{{ name | uppercase }}
We can also use filters with $filter
service.
For instance, to use the lowercase JavaScript filter:
app.controller('MyController', ['$scope', '$filter', function($scope, $filter) { $scope.name = $filter('lowercase')('Angular'); }]);
To pass an argument to a filter in HTML, we pass it with a colon after the filter name.
To pass in multiple arguments, we can append a colon after each argument.
For example, the number filter allows us to limit the number of decimal places.
To pass the argument 2, we'll append :2
to the number filter:
<!-- Displays: 123.46 --> {{ 123.456789 | number:2 }}
We can use multiple filters at the same time by using two or more pipes.
To create a filter, we put it under its own module.
The following code creates a filter that capitalizes the first character of a string.
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js"></script>
<!--from w ww .j a v a 2 s. co m-->
</head>
<body ng-app>
<h2>{{ 'this is a test' | capitalize }}</h2>
<script>
angular.module('myApp', ['myApp.filters']);
angular.module('myApp.filters', [])
.filter('capitalize', function() {
return function(input) {
// input will be the string we pass in
if (input) {
return input[0].toUpperCase() + input.slice(1);
}
}
});
</script>
</body>
</html>
The code above is rendered as follows: