gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:22:09 25 4
gpt4 key购买 nike

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

中的变量

有关示例,请参阅此 fiddle : 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;
}
});

关于javascript - Angularjs。如何将变量作为参数传递给自定义过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15659559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com