gpt4 book ai didi

angularjs - 与父值匹配的 Angular 嵌套ng-repeat过滤器项

转载 作者:行者123 更新时间:2023-12-04 05:06:48 24 4
gpt4 key购买 nike

我将2个数组传递给我的 View 。我希望嵌套循环仅显示其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 $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>

在将对象传递到 Angular 之前,是否应在节点中对对象进行过滤,这是否可能是最佳做法?谢谢!

最佳答案

您可以通过以下两种方法进行操作...您可以创建一个仅返回子级的函数:

$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 getChildren(parent)">

您可以定义一个过滤器来做同样的事情:
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;
};
});

的HTML:
<div ng-repeat="child in arr2|children:parent">

不过,这两种方法都会在每个摘要周期执行一次。如果您有大量的元素,则肯定要提高性能。我认为最好的方法是对得到的结果进行预处理,在arr1中的每个对象中仅添加带有其子对象的子数组(此处使用array.filter代替for循环和array.forEach):
arr1.forEach(function(parent) {
parent.children = arr2.filter(function(value) {
return value.parent_id === parent.id;
};
});

然后在html中,您已经在与父级一起工作,因此您可以重复其childs属性:
<div ng-repeat="child in parent.children">

关于angularjs - 与父值匹配的 Angular 嵌套ng-repeat过滤器项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27136930/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com