Angularjs 与父值匹配的角度嵌套ng重复筛选项
我将2个数组传递给我的视图。我希望嵌套循环仅显示其parent_id值与parent.id匹配的位置。例如Angularjs 与父值匹配的角度嵌套ng重复筛选项,angularjs,filter,nested,repeat,Angularjs,Filter,Nested,Repeat,我将2个数组传递给我的视图。我希望嵌套循环仅显示其parent_id值与parent.id匹配的位置。例如 arr1 = {"0":{"id":326,"parent_id":0,"title":"Mellow Mushroom voucher","full_name":"Patrick","message":"The voucher says $10 Voucher; some wording on the printout says, \"This voucher is valid for
arr1 = {"0":{"id":326,"parent_id":0,"title":"Mellow Mushroom voucher","full_name":"Patrick","message":"The voucher says $10 Voucher; some wording on the printout says, \"This voucher is valid for $20 Pizza\" but my purchase price or amount paid also says $20. Shouldn't that be $10","type":"Deals"}};
arr2 = {"0":{"id":327,"parent_id":326,"title":"Re: Mellow Mushroom voucher","full_name":"Patrick Williams","message":"Some message here","type":null};
...
<div data-ng-repeat = "parent in arr1">
<span>{{parent.title}}<span>
<div data-ng-repeat="child in arr2 | only-show-where-child.parent_id == parent.id">
<li>{{child.body}}</li>
</div>
</div>
arr1={“0”:{“id”:326,“家长id”:0,“头衔”:“香菇券”,“全名”:“Patrick”,“message”:“券上写着10美元券;打印件上的一些文字说,“这张券有效期为20美元披萨”,但我的购买价格或支付的金额也写着20美元。这不应该是10美元吗;
arr2={“0”:{“id”:327,“家长id”:326,“标题”:“Re:Mellow Muslium凭证”,“全名”:“Patrick Williams”,“消息”:“此处有消息”,“键入”:null};
...
{{parent.title}
{{child.body}
这是angular of中的可能/最佳实践吗?在将对象传递到angular之前,我是否应该过滤节点中的对象?谢谢!解决方案取决于数组更改的频率和数组的大小 第一种解决方案是使用过滤器。但在这种情况下,它将被调用至少两次(以确保结果“稳定”——选择相同的元素) 另一个解决方案是自己制作原始数组,并在那里准备“查看”版本的数组。我个人更喜欢第二个,因为它更明确 然而,如果您可以在应用程序的其他部分重用“find-the0child”过滤器,您可以使用第一个过滤器-AngularJS将仅在修改原始数组后重新运行过滤器
如果需要,我可以在这里提供这些选项之一的实施示例-添加注释以回答。如果使用过滤器,
data ng
可以实现相同的结果
<div data-ng-repeat="parent in arr1">
<span>{{parent.title}}<span>
<div data-ng-repeat="child in arr2" data-ng-if="child.parent_id == parent.id">
<li>{{child.body}}</li>
</div>
</div>
{{parent.title}
{{child.body}
有几种方法可以实现这一点……您可以创建一个只返回子级的函数:
$scope.getChildren = function(parent) {
var children = [];
for (var i = 0; i < arr2.length; i++) {
if (arr2[i].parent_id == parent.id) {
children.push(arr2[i]);
}
}
return children;
};
然后,在html中,您已经在使用父对象,以便可以重复其子对象属性:
<div ng-repeat="child in parent.children">
我假设arr1和arr2实际上是数组,而不仅仅是对象,如果是的话,那么你能编辑你的代码吗?我自己也会,但我不想知道这是否是问题的一部分。它们是对象,对不起!对每个对象都进行了编辑。谢谢你的多方面回答。非常有效!先生,你是一颗宝石!
myApp.filter('children', function() {
return function(input, parent) {
var children = [];
for (var i = 0; i < input.length; i++) {
if (input[i].parent_id == parent.id) {
children.push(input[i]);
}
}
return children;
};
});
<div ng-repeat="child in arr2|children:parent">
arr1.forEach(function(parent) {
parent.children = arr2.filter(function(value) {
return value.parent_id === parent.id;
};
});
<div ng-repeat="child in parent.children">