Подтвердить что ты не робот

Angularjs. Как передать переменную как аргумент пользовательскому фильтру?

У меня есть следующий HTML

<span class="items-count">{{items | countmessage}}</span>

И следующий фильтр, чтобы отобразить правильное количество сообщений

    app.filters
    .filter('countmessage', function () {
        return function (input) {
            var result = input.length + ' item';
            if (input.length != 1) result += 's';
            return message;
        }
    });

но я хочу использовать разные слова вместо "item (s)", поэтому я изменил фильтр

    app.filters
    .filter('countmessage', function () {
        return function (input, itemType) {
            var result = input.length + ' ' + itemType;
            if (input.length != 1) result += 's';
            return message;
        }
     });

он работает, когда я использую такую ​​строку

<span class="items-count">{{items | countmessage:'car'}}</span>

но не работает с переменной из области $scope, возможно ли использовать переменную $scope

<span class="items-count">{{items | countmessage:itemtype}}</span>

Спасибо

4b9b3361

Ответ 1

Да, можно использовать переменную из области $scope.

Смотрите эту скрипку для примера: 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;
        }
     });