简体   繁体   English

AngularJS-ng-repeat生成空元素

[英]Angularjs - ng-repeat generating empty elements

I have a array which have improper key order, like 我有一个键顺序不正确的数组,例如

1: Array[1]
2: Array[2]
4: Array[3]
7: Array[14]
21: Array[1]
22: Array[1]
23: Array[1] 

So when I iterate using ng-repeat , empty elements and generated for key values which are not there. 因此,当我使用ng-repeat进行迭代时,会生成空元素并生成不存在的键值。

So here it will generate elements for keys 1 and 2, and as there is no key 3, it will generate an empty div there.Same happens after 4.three empty elements are generated.How can this be fixed ? 所以在这里它将为键1和2生成元素,而由于没有键3,它将在那里生成一个空的div.4之后又发生了三个空元素的生成,如何解决?

You can either fix the array by creating a new array with proper values or you can add a check in the view for not null or undefined. 您可以通过创建具有适当值的新数组来修复数组,也可以在视图中添加检查结果是否为非null或undefined。

Fix the array 修复数组

var myArray = [[1], [1,2], null, [1,2,3]];
var newArray = [];
angular.forEach(function (myArray, function (a) {
  if (a & a.length) { 
    newArray.push(a);
  }
})l;

Now you can use the new array to render the view 现在您可以使用新数组来渲染视图

Or fix in the view 或在视图中修复

<div ng-repeat="item in myArray">
   <div ng-if="item !== null && item !== undefined">
   </div>
</div>

Why you don't use object? 为什么不使用对象?

"array":[
    {"key":"1", "content":[]}, 
    {"key":"2", "content":[]}, 
    {"key":"5", "content":[]}, 
    {"key":"3", "content":[]}
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM