I have following HTML
<span class="items-count">{{items | countmessage}}</span>
And following filter to show right count message
app.filters .filter('countmessage', function () { return function (input) { var result = input.length + ' item'; if (input.length != 1) result += 's'; return message; } });
but I want use different words instead 'item(s)', so I modified the filter
app.filters .filter('countmessage', function () { return function (input, itemType) { var result = input.length + ' ' + itemType; if (input.length != 1) result += 's'; return message; } });
it works when I use a string like that
<span class="items-count">{{items | countmessage:'car'}}</span>
but doesn't work with a variable from the $scope, is it possible to use $scope variable
<span class="items-count">{{items | countmessage:itemtype}}</span>
Thanks
To create custom filter, we need to just register the filter in factory function in our module. This uses the "filterProvider" internally. By default new filter function takes the input value as the first argument and factory function will return the new filter.
In AngularJS, you can also inject the $filter service within the controller and can use it with the following syntax for filter. Syntax: $filter("filter")(array, expression, compare, propertyKey) function myCtrl($scope, $filter) { $scope. finalResult = $filter("filter")( $scope.
Using filters in view templates Filters can be applied to the result of another filter. This is called "chaining" and uses the following syntax: {{ expression | filter1 | filter2 | ... }} E.g. the markup {{ 1234 | number:2 }} formats the number 1234 with 2 decimal points using the number filter.
Yes, it is possible to use variable from the $scope
See this fiddle for an example: http://jsfiddle.net/lopisan/Kx4Tq/
HTML:
<body ng-app="myApp"> <div ng-controller="MyCtrl"> <input ng-model="variable"/><br/> Live output: {{variable | countmessage : type}}!<br/> Output: {{1 | countmessage : type}}! </div> </body>
JavaScript:
var myApp = angular.module('myApp',['myApp.filters']); function MyCtrl($scope) { $scope.type = 'cat'; } angular.module('myApp.filters', []) .filter('countmessage', function () { return function (input, itemType) { var result = input + ' ' + itemType; if (input > 1) result += 's'; return result; } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With