我正在尝试 angularjs 框架。
有 JSON 形式的统计信息,例如:
[{"Region": "USA",
"People":[{"Id":2,"Name":"Pals"}, {"Id":1,"Name":"Andrew"}]},
{"Region": "India",
"People":[{"Id":2,"Name":"Ram"}, {"Id":1,"Name":"Sam"}]}];
希望提供一个搜索选项来搜索地区和人名。 当人名匹配时,它必须与地区一起显示。 因此,我尝试编写一个过滤器来过滤 ng-repeat。
Search : <input id="search" type="text" class="form-control" ng-model="Search" placeholder="enter text here"/>
<br/><br/>
<div ng-repeat="pregion in stats | searchFilter : Search">
{{pregion.Region}}
<div ng-repeat="p in pregion.People">
{{p.Name}}
</div>
</div>
但是过滤器似乎返回多个数组,导致错误:$rootScope:infdig 无限$digest Loop。
plunker @ http://plnkr.co/edit/Bm8rlizBf49sZ93pDLfS?p=preview 中的完整代码
任何人都可以提出解决方案或替代方法吗?谢谢。
最佳答案
在我看来,问题在于您正在手动复制部分过滤的区域,并且存在拼写错误(丢失区域['People']),因此您的过滤结果在再次运行时与过滤器不匹配。这是我将使用的解决方案:
angular.forEach(input, function(v){
if(v.Region.toLowerCase().indexOf(search.toLowerCase()) !== -1){
cat.push(v);
} else {
mod = [];
tempCat = {};
angular.forEach(v.People, function(u){
if(u.Name.toLowerCase().indexOf(search.toLowerCase()) !== -1){
mod.push(u);
}
});
if (mod.length > 0) {
v = angular.copy(v);
v.People = mod;
cat.push(v);
}
}
});
return cat;
但如果您确实想从非区域结果中折叠出该区域,则可以直接修复该类型:
angular.forEach(input, function(v){
if(v.Region.toLowerCase().indexOf(search.toLowerCase()) !== -1){
cat.push(v);
} else {
mod = [];
tempCat = {};
angular.forEach(v.People, function(u){
if(u.Name.toLowerCase().indexOf(search.toLowerCase()) !== -1){
mod.push(u);
}
});
if (mod.length > 0) {
tempCat.Categoryid = v.Categoryid;
tempCat.CategoryName = v.CategoryName;
tempCat.CategoryOrder = v.CategoryOrder;
tempCat.CategoryImage = v.CategoryImage;
tempCat.People = mod;
cat.push(tempCat);
}
}
});
return cat;
关于json - Angularjs ng-repeat 在 JSON 的多层上进行重复过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25332786/