代码可在此处获取:https://plnkr.co/edit/gbbsEnXxVpLsxvtKsDxw?p=preview 。过滤器 filter: { a : 'x' }
有效,仅显示一行。
问题:
- 似乎
filter: { a : 'xxx' }
会匹配a
中的任何文本,只要该文本包含字符串xxx
即可。如果我想要精确匹配怎么办? - 如何实现:如果
a = 'xxx'或b = 3
不使用c
则显示所有行? - 也许在 `model.dashbardRows 上使用 JavaScript 代码会更好?
dashboard.component.js
(function () {
'use strict';
angular.module('testModule', [])
.component('dashboard', {
templateUrl: 'dashboard.component.html',
controllerAs: 'model',
controller: [controller]
});
function controller() {
var model = this;
model.dashboardRows = [
{a:'xxx', b:1, c:'ss'},
{a:'yyy', b:2, c:'tt'},
{a:'zzz', b:3, c:'uu'}];
}
})();
dashboard.component.html
<div>
Test
<table>
<tr ng-repeat="i in model.dashboardRows | filter: { a : 'x' }">
<td>{{i.a}}</td>
<td>{{i.b}}</td>
</tr>
</table>
</div>
最佳答案
正如@Valery 建议的那样,使用自定义过滤器是解决此问题的最佳解决方案。
Here is fork using custom filter(multiple conditions)
仪表板.component.js
.filter("optionalFilter",function(){
//console.log("filter loads");
return function(items, firstArgument,secondArgument){
//console.log("item is ",items); // it is value upon which you have to filter
//console.log("firstArgument is ",firstArgument);
//console.log("secondArgument ",secondArgument);
var filtered = [];
angular.forEach(items, function(value, key) {
//console.log("val ::",value);
if(value.a == firstArgument || value.b == secondArgument){
// console.log("val ::",value.a);
this.push(value);
}
}, filtered);
//console.log("val ::",filtered);
return filtered;
}
仪表板.component.html
<tr ng-repeat="i in model.dashboardRows | optionalFilter:'aaa':2">
有用的引用:
关于javascript - AngularJs 过滤器的条件为 "or"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39554350/