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

Angularjs. How can I pass variable as argument to custom filter?

本文关键字:参数传递 自定义 过滤器 变量 Angularjs      更新时间:2023-09-26

我有以下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>

不能与$作用域中的变量一起工作,是否可以使用$作用域变量

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

谢谢

是的,可以使用$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;
        }
     });