我正在尝试使用多列过滤角度js数组。
例如|过滤器:{sender:' fred',reciever:' josh'} |过滤器:{发件人:' josh',收件人:' fred'}
但它似乎不起作用,请查看下面的完整代码
<div ng-repeat="msg in messages | filter:{sender: 'fred', reciever: 'josh'} | filter:{sender: 'josh', reciever: 'fred'}">
Sender : {{ msg.sender }} MSg : {{ msg.msg }} Reciever : {{ msg.reciever }}
</div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.messages = [
{sender:'fred', reciever:'josh', msg:'HI'},
{sender:'josh', reciever:'fred', msg:'i DEY'},
{sender:'fred', reciever:'josh', msg:'Hello'}
];
});
</script>
答案 0 :(得分:1)
我更愿意过滤控制器中的消息。 DOM过滤器可能会导致性能问题。见:Using Controller $filters to prevent $digest performance issues
但这基本上有效:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.messages = [
{sender:'fred', receiver:'josh', msg:'HI'},
{sender:'josh', receiver:'fred', msg:'i DEY'},
{sender:'josh', receiver:'racheal', msg:'hw re u2?'},
{sender:'barack', receiver:'angela', msg:'Dear'},
{sender:'fred', receiver:'josh', msg:'Hello'},
{sender:'angela', receiver:'barack', msg:'Moin'},
{sender:'josh', receiver:'racheal', msg:'hw re u?'}
];
}).filter('myfilter', function() {
return function(input, filter) {
return input.filter(function(e1){
return filter.find(function(e2) {
return e1.sender === e2.sender && e1.receiver === e2.receiver;
});
});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="msg in (messages | myfilter:[{sender: 'fred', receiver: 'josh'},{sender: 'josh', receiver: 'fred'}])">
Sender : {{ msg.sender }} MSg : {{ msg.msg }} Reciever : {{ msg.reciever }}
</div>
</div>
它遵循没有DOM过滤的解决方案,我认为是一种更好的方法:
var app = angular.module('myApp', []);
function filter(input, filter) {
return input.filter(function(e1){
return filter.find(function(e2) {
return e1.sender === e2.sender && e1.receiver === e2.receiver;
});
});
}
app.controller('myCtrl', function($scope) {
var messages = [
{sender:'fred', receiver:'josh', msg:'HI'},
{sender:'josh', receiver:'fred', msg:'i DEY'},
{sender:'josh', receiver:'racheal', msg:'hw re u2?'},
{sender:'barack', receiver:'angela', msg:'Dear'},
{sender:'fred', receiver:'josh', msg:'Hello'},
{sender:'angela', receiver:'barack', msg:'Moin'},
{sender:'josh', receiver:'racheal', msg:'hw re u?'}
];
var name1 = 'fred';
var name2 = 'josh';
var myFilter = [{sender: name1, receiver: name2},{sender: name2, receiver: name1}];
$scope.messages = filter(messages, myFilter);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="msg in messages">
Sender : {{ msg.sender }} MSg : {{ msg.msg }} Reciever : {{ msg.reciever }}
</div>
</div>