Con*_*ror 28 javascript templates loops angularjs
我有一个具有一系列对象属性的对象,它们具有以下类似结构(这是数据从服务返回的方式):
{
"1": {
"type": "foo",
"name": "blah"
},
"2": {
"type": "bar"
},
"3": {
"type": "foo"
},
"4": {
"type": "baz"
},
"5": {
"type": "test"
}
}
Run Code Online (Sandbox Code Playgroud)
当我进行ng-repeat时,我可以遍历所有这5个对象,例如:
<div ng-repeat="item in items">{{item.type}}</div>
Run Code Online (Sandbox Code Playgroud)
但是,我真正想做的只是迭代那些不是"foo"类型的项目,即3次迭代而不是5次.我知道过滤器可以某种方式用来做到这一点,但我不知道如何.我尝试了以下方法:
<div ng-repeat="item in items| !filter:{type:'foo'}">{{item.type}}</div>
Run Code Online (Sandbox Code Playgroud)
但这不起作用.实际上,即使只执行以下操作来限制只有2个对象(那些使用item.type ==="foo"),它也不起作用并进行5次迭代:
<div ng-repeat="item in items| filter:{type:'foo'}">{{item.type}}</div>
Run Code Online (Sandbox Code Playgroud)
从本质上讲,我想做类似的事情:
<div ng-repeat="item in items" ng-if="item.type !=='foo'>{{item.type}}</div>
Run Code Online (Sandbox Code Playgroud)
但是,我知道一个不起作用.
Vai*_*uri 45
回答不多,但这可能会有所帮助:
如果要对给定对象的孙(或更深)进行过滤,可以继续构建对象层次结构.例如,如果要对'thing.properties.title'进行过滤,则可以执行以下操作:
<div ng-repeat="thing in things | filter: { properties: { title: title_filter } }">
Run Code Online (Sandbox Code Playgroud)
您还可以通过将对象添加到过滤器对象来过滤对象的多个属性:
<div ng-repeat="thing in things | filter: { properties: { title: title_filter, id: id_filter } }">
Run Code Online (Sandbox Code Playgroud)
'not equals'的语法稍微偏离,请尝试以下方法:
<div ng-repeat="thing in things | filter: { properties: { title: '!' + title_filter } }">
Run Code Online (Sandbox Code Playgroud)
Kay*_*ave 16
过滤器适用于数组,但您有一个对象文字.
因此,您可以将对象文字转换为数组,也可以创建自己的过滤器而不是对象文字.
如果你不需要那些索引值,那么转换为数组可能是你最好的选择(这里有一个小数组工作:http://jsfiddle.net/NqA8d/3/):
$scope.items = [{
"type": "foo",
"name": "blah"
}, {
"type": "bar"
}, {
"type": "foo"
}, {
"type": "baz"
}, {
"type": "test"
}];
Run Code Online (Sandbox Code Playgroud)
如果你想做一个过滤器,这是一种方法:
myApp.filter('myFilter', function () {
return function (items, search) {
var result = [];
angular.forEach(items, function (value, key) {
angular.forEach(value, function (value2, key2) {
if (value2 === search) {
result.push(value2);
}
})
});
return result;
}
});
Run Code Online (Sandbox Code Playgroud)
那个小提琴:http: //jsfiddle.net/NqA8d/5/
hug*_*ige 16
虽然我同意转换对象可能是最好的选择,但您也可以使用此过滤器功能:
angular.module('app').filter('objectByKeyValFilter', function () {
return function (input, filterKey, filterVal) {
var filteredInput ={};
angular.forEach(input, function(value, key){
if(value[filterKey] && value[filterKey] !== filterVal){
filteredInput[key]= value;
}
});
return filteredInput;
}});
Run Code Online (Sandbox Code Playgroud)
像这样:
<div ng-repeat="(key, value) in data | objectByKeyValFilter:'type':'foo'">{{key}}{{value.type}}</div>
Run Code Online (Sandbox Code Playgroud)
另见Plunker.