使用 orderBy 和 track by 删除 ng-repeat 中的元素失败 [英] deleting an element in ng-repeat with orderBy and track by is failing
问题描述
这是代码
<tr ng-repeat="collection in collections | orderBy:'-modifiedDate' track by $index" ng-init="listIndex = $index">
如果我删除 orderBy:'-modifiedDate'
,则删除特定元素的效果很好.但是,我需要以排序方式呈现集合/数组,这就是我有 orderBy 的原因.
如果我不从代码中删除 orderBy:'-modifiedDate'
并且我删除了一个随机元素,比如位置 7,那么被删除的元素总是最后一个.>
我不得不使用 ng-init
,因为我在上面显示的 ng-repeat
中有另一个 ng-repeat
.我这样调用删除函数,ng-click="deleteRow(listIndex)"
当你使用 orderBy 时,angular 会在作用域中创建另一个集合",并改变其元素的顺序,但原始的集合"保持不变,例如如果:
$scope.collections = [{名称:'第一个元素',id:'1'},{名称:'第二个元素',id:'2'},{名称:'第三个元素',id:'3'}];<tr ng-repeat="collection in collections | orderBy:'id':true track by $index">
$scope.collections[2] 仍然是 { name: '3rd element', id: '3' }
这是您可以做的,您可以为由 angular 创建的排序集合命名:
然后你可以使用 $scope.sortedCollections[2] 代替
Here is the code
<tr ng-repeat="collection in collections | orderBy:'-modifiedDate' track by $index" ng-init="listIndex = $index">
If I remove orderBy:'-modifiedDate'
, the deletion on a specific element is working great. However, I need the collection/array to be rendered in sorted way that's why I have orderBy.
If I don't delete the orderBy:'-modifiedDate'
from the code and I delete a random element say on position 7, the element that gets deleted is the very last always.
I had to use ng-init
since I have another ng-repeat
inside the ng-repeat
shown above. I call the delete function like this, ng-click="deleteRow(listIndex)"
解决方案 When you use orderBy, angular creates another "collections" in the scope, and changes the order of its elements, but the original "collections" stays the same, for example if :
$scope.collections = [
{ name: '1st element', id: '1' },
{ name: '2nd element', id: '2' },
{ name: '3rd element', id: '3' }
];
<tr ng-repeat="collection in collections | orderBy:'id':true track by $index">
$scope.collections[2] would still be { name: '3rd element', id: '3' }
Here's what you can do, you can give a name to that sorted collection created by angular :
<tr ng-repeat="collection in sortedCollections = (collections | orderBy:'id':true) track by $index">
And then you could use $scope.sortedCollections[2] instead
这篇关于使用 orderBy 和 track by 删除 ng-repeat 中的元素失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文
登录
关闭
扫码关注1秒登录
发送“验证码”获取
|
15天全站免登陆