31

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

1 Answer 1

42

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;
        }
     });
Sign up to request clarification or add additional context in comments.

4 Comments

ok thanks, I found it already, I just missed my variable for the current scope, it works now.
Can we generate the $scope.type dynamically through user input? Such as: <input type='text' ng-model='searchTerm'>?
@Clever: Yes it can be done, just add <input ng-model="type"/> to the HTML part of the fiddle.
Thanks. After a few hours of headbanging yesterday, I found my issue was actually a child-parent scope inheritance problem stemming from ng-include.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.