[英]Adding to index in angular filter
For various reasons I am using an Angular filter to add to the itemlist that will be used by ng-repeat (basically I need to group certain items under a subheading in a table). 由于各种原因,我正在使用Angular过滤器将其添加到ng-repeat将使用的项目列表中(基本上,我需要将某些项目分组在表格的子标题下)。
app.filter('tableFilter',
function(){
return function(items){
if (!items){
return;
}
var transformed = [];
for (var i = 0; i < items.length; i++){
if (items[i].classid){
if (i === 0 || items[i].classid !== items[i-1].classid){
transformed.push({classheader : true});
}
else{
items[i].classheader = false;
}
}
transformed.push(items[i]);
}
return transformed;
}
}
);
The good news is that it works. 好消息是它有效。 The bad news is that it generates errors, the first one being:
坏消息是它会产生错误,第一个是:
[$rootScope:infdig]
[$ rootScope:infdig]
http://errors.angularjs.org/1.2.23/ $rootScope/infdig?p0=10&p1=%5B%5B%22fn%3…%7C%20''%3B%20newVal%3A%20%5C%22%5C%22%3B%20oldVal%3A%20undefined%22%5D%5Dhttp://errors.angularjs.org/1.2.23/ $ rootScope / infdig?p0 = 10&p1 =%5B%5B%22fn%3…%7C%20''%3B%20newVal%3A%20%5C%22 %5C%22%3B%20oldVal%3A%20undefined%22%5D%5D
Which is to do with infinite loops in the digest cycle. 这与摘要循环中的无限循环有关。 I suspect that by adding to the item list I am corrupting the array /
$index
used by ng-repeat
. 我怀疑通过添加到项目列表中,我正在破坏
ng-repeat
所使用的数组/ $index
。
I can transform the itemlist in the controller / service but that does not seem correct since this is basically only being done for presentation. 我可以在控制器/服务中转换项目列表,但这似乎并不正确,因为这基本上只是为了演示而已。
Do not change properties from items on filter. 不要更改过滤器上项目的属性。 This will invoke again the forEach loop.
这将再次调用forEach循环。
remove this line: items[i].classheader = false; 删除以下行:items [i] .classheader = false;
if you need to update classheader flag on transformed array, you can change your code to use angular copy: 如果您需要在转换后的数组上更新classheader标志,则可以更改代码以使用角度复制:
app.filter('tableFilter',
function() {
return function(items){
if (!items){
return;
}
var transformed = [];
for (var i = 0; i < items.length; i++) {
var item = angular.copy(items[i]);
if (items[i].classid) {
if (i === 0 || items[i].classid !== items[i-1].classid) {
transformed.push({classheader : true});
} else {
item.classheader = false;
}
}
transformed.push(item);
}
return transformed;
};
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.