Reputation: 2661
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
Upvotes: 31
Views: 42329
Reputation: 7830
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;
}
});
Upvotes: 42