Angularjs 在 orderBy 之后错误的 $index [英] Angularjs wrong $index after orderBy

查看:13
本文介绍了Angularjs 在 orderBy 之后错误的 $index的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Angular.js 的新手,在排序数组和处理排序数据时遇到了一些问题.

I am new to Angular.js and have some problems sorting my array and working on that sorted data.

我有一个包含项目的列表,并希望按Store.storeName"对其进行排序,该列表目前正在运行.但是在对数据进行排序后,我的删除功能不再起作用.我认为那是因为排序后$index 是错误的,因此删除了错误的数据.

I have a list with items and want so sort it by "Store.storeName", which is working so far. But after sorting the data, my delete-function is not working anymore. I think thats because the $index is wrong after sorting, and so the wrong data is deleted.

我该如何解决?在范围内而不是视图中对数据进行排序?如何做到这一点?

How can I solve that? Ordering the data in the scope and not in the view? How to do that?

这是一些相关的代码:

在视图中:

<tr ng-repeat="item in items | orderBy:'Store.storeName'">
                <td><input class="toggle" type="checkbox" ng-model="item.Completed"></td>
                <td>{{item.Name}}</td>
                <td>{{item.Quantity}} Stk.</td>
                <td>{{item.Price || 0 | number:2}} €</td>                
                <td>{{item.Quantity*item.Price|| 0 | number:2}} €</td>
                <td>{{item.Store.storeName}}</td> 
                <td><a><img src="img/delete.png" ng-click="removeItem($index)">{{$index}}</a></td>
            </tr>

在我的控制器中,我有这个删除功能,它应该删除特定的数据:

And in my controller I have this delete function, which should delete the specific data:

$scope.removeItem = function(index){
        $scope.items.splice(index,1);
    }

这在视图中订购之前效果很好.如果遗漏了什么重要的东西,请现在告诉我.

This works nicely before ordering in the View. If something important is missing, please let me now.

谢谢!

推荐答案

改为使用 $index - 正如您所注意到的 - 将指向排序/过滤数组中的索引,您可以将项目本身传递给您的 removeItem 函数:

Instead or relaying on the $index - which - as you have noticed - will point to the index in a sorted / filtered array, you can pass the item itself to your removeItem function:

<a><img src="img/delete.png" ng-click="removeItem(item)">{{$index}}</a>

并修改removeItem函数以使用数组的indexOf方法查找索引,如下所示:

and modify the removeItem function to find an index using the indexOf method of an array as follows:

$scope.removeItem = function(item){
   $scope.items.splice($scope.items.indexOf(item),1);
}

这篇关于Angularjs 在 orderBy 之后错误的 $index的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆