Angularjs.如何将变量作为参数传递给自定义过滤器?

Igo*_*rCh 29 javascript angularjs

我有以下HTML

<span class="items-count">{{items | countmessage}}</span>
Run Code Online (Sandbox Code Playgroud)

并按照过滤器显示正确的计数消息

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

但我想使用不同的单词代替'item(s)',所以我修改了过滤器

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

当我使用这样的字符串时它会起作用

<span class="items-count">{{items | countmessage:'car'}}</span>
Run Code Online (Sandbox Code Playgroud)

但是不能使用$ scope中的变量,是否可以使用$ scope变量

<span class="items-count">{{items | countmessage:itemtype}}</span>
Run Code Online (Sandbox Code Playgroud)

谢谢

lop*_*san 38

是的,可以使用来自的变量 $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>
Run Code Online (Sandbox Code Playgroud)

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;
        }
     });
Run Code Online (Sandbox Code Playgroud)