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

前端之家收集整理的这篇文章主要介绍了angularjs – 与父值匹配的Angular嵌套ng-repeat过滤器项前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我传递了2个数组到我的视图.我希望我的嵌套循环只显示其parent_id值与parent.id匹配的位置.例如.
  1. 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"}};
  2. arr2 = {"0":{"id":327,"parent_id":326,"title":"Re: Mellow Mushroom voucher","full_name":"Patrick Williams","message":"Some message here","type":null};
  3.  
  4. ...
  5. <div data-ng-repeat = "parent in arr1">
  6. <span>{{parent.title}}<span>
  7. <div data-ng-repeat="child in arr2 | only-show-where-child.parent_id == parent.id">
  8. <li>{{child.body}}</li>
  9. </div>
  10. </div>

这是角度中的可能/最佳实践吗?我应该在将节点传递给角度之前过滤节点中的对象吗?谢谢!

有几种方法可以做到这一点……你可以创建一个只返回孩子的函数
  1. $scope.getChildren = function(parent) {
  2. var children = [];
  3. for (var i = 0; i < arr2.length; i++) {
  4. if (arr2[i].parent_id == parent.id) {
  5. children.push(arr2[i]);
  6. }
  7. }
  8. return children;
  9. };

HTML:

  1. <div ng-repeat="child in getChildren(parent)">

你可以定义一个过滤器来做同样的事情:

  1. myApp.filter('children',function() {
  2. return function(input,parent) {
  3. var children = [];
  4. for (var i = 0; i < input.length; i++) {
  5. if (input[i].parent_id == parent.id) {
  6. children.push(input[i]);
  7. }
  8. }
  9. return children;
  10. };
  11. });

HTML:

  1. <div ng-repeat="child in arr2|children:parent">

这两种方法都会执行每个摘要周期.如果您有大量元素,那么您肯定希望提高性能.我认为最好的方法是在获得它们时预处理这些结果,在arr1中只为其子项添加子数组(这里使用array.filter而不是for循环和array.forEach):

  1. arr1.forEach(function(parent) {
  2. parent.children = arr2.filter(function(value) {
  3. return value.parent_id === parent.id;
  4. };
  5. });

然后在html中你已经在使用父级了,所以你可以重复它的子属性

  1. <div ng-repeat="child in parent.children">

猜你在找的Angularjs相关文章