[英]Angular JS ng-repeat with different filters
I have a small question.我有一个小问题。
I have this json object that我有这个 json 对象
var map = {
key1 : {filter:'bytes',value: 100000000},
key2 : {filter:'ratio',value: 1.25}
};
I would like to use it with ng-repeat
我想将它与
ng-repeat
一起使用
<div ng-repeat="key in map"> {{key.value | key.filter}}</div>
How can I accomplish this behaviour to get predefined filters implemented while in ng-repeat
?如何在
ng-repeat
实现此行为以实现预定义的过滤器?
If i understand right, you want get something like如果我理解正确,你想要得到类似的东西
<div ng-repeat="key in map"> {{100000000 | bytes }}</div>
<div ng-repeat="key in map"> {{1.25 | ratio }}</div>
But angular raise error when try parse expression, instead get filter name from variable.但是尝试解析表达式时会引发角度错误,而是从变量中获取过滤器名称。 So you can add a filter, that would be apply to source filter by name, something like
因此,您可以添加一个过滤器,该过滤器将按名称应用于源过滤器,例如
.filter('applyFilter',function($filter){
return function(source, filterName){
return $filter(filterName)(source);
}
})
angular.module('app', []) .controller('ctrl', function($scope) { $scope.map = { key1: { filter: 'bytes', value: 100000000 }, key2: { filter: 'ratio', value: 1.25 } }; }).filter('bytes',function(){ return function(a){ return a + ' bytes'; } }).filter('ratio',function(){ return function(a){ return 'ratio: ' + a; } }).filter('applyFilter',function($filter){ return function(source, filterName){ return $filter(filterName)(source); } });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.js"></script> <div ng-app="app" ng-controller="ctrl"> <div ng-repeat="key in map"> {{key.value | applyFilter: key.filter }}</div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.