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>
不能与$作用域中的变量一起工作,是否可以使用$作用域变量
<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;
}
});
相关文章:
- 如何将自定义参数传递到FullCalendar事件提要
- 如何调用另一个js文件中的函数或触发一个自定义事件,该事件将参数作为Jquery中的数据对象传递
- extjs-使用传递的参数创建自定义函数
- 将角度工厂中的参数用于自定义标头
- 调用插件外部的自定义函数并传递参数
- 使用函数参数的自定义时间表
- 如何在jQuery PrintArea中传递自定义html标签
- 条带结账.js - 将自定义参数传递给令牌回调
- require.js-未定义的模块作为参数传递以定义回调
- JS用self作为参数创建自定义对象
- 是否可以在casper.base64encode()中传递自定义请求头?
- 调用带有不同参数的自定义对象实例
- 使用jQuery根据URL参数显示自定义内容的最佳方式是什么?
- 如何通过Web-Workers传递自定义类实例
- 在AngularJS中传递额外的参数给自定义排序函数
- jQuery+JavaScript:使用单个对象作为参数创建自定义ajax调用函数
- 如何创建使用前缀作为参数的自定义方法
- 通过在JavaScript中传递自定义参数来查询数据表
- ecmascript 5 -用固定参数的自定义顺序套用Javascript函数
- 如何在Backbone.js中传递自定义函数从路由器到视图到模板?