繁体   English   中英

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

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

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

谢谢

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM