如何使用AngularJS中的过滤器从数组中删除项?

时间:2022-04-16 19:46:56

When I click on tr without any filter, my function array.splice() works. Indexes in the array are in the correct order, so the array.splice() works.

当我没有任何过滤器点击tr时,我的函数array.splice()工作。数组中的索引按正确的顺序排列,因此array.splice()可以工作。

When the filter is enable, Indexes in the array are not updated and still in the same order. So array.splice() removes the wrong item.

当启用筛选器时,数组中的索引不会被更新,并且仍然保持相同的顺序。因此,array.splice()删除了错误的项。

    <span ng-click="orderP0 = 'statut_name'; reversePO=!reversePO">order</span>

    <tr ng-repeat="project in projects | orderBy : orderPO : reverse track by $index" ng-click="remove($event,$index,projects)">
        <span class="label" ng-bind="project.statut_name"></span>
    </tr>

    $scope.remove = function($event,index,array){
        array.splice(index,1);
    };

How to update index in the array ? Or How to removes the right item ?

如何更新数组中的索引?或者如何删除正确的项目?

2 个解决方案

#1


8  

The simplest solution would be to change your remove function to take in the project instead of the index.

最简单的解决方案是更改您的remove函数,而不是索引。

$scope.remove = function(project){
    for(var i = $scope.projects.length - 1; i >= 0; i--){
        if($scope.projects[i].statut_name == project.statut_name){
            $scope.projects.splice(i,1);
        }
    }
}

Example Plunker: http://plnkr.co/edit/51SNVMQjG3dsmpYI5RyY?p=preview

例子恰好:http://plnkr.co/edit/51SNVMQjG3dsmpYI5RyY?p=preview

#2


21  

It's easier to splice you projects in the actual position of the element in the array using indexOf.

使用indexOf更容易将项目拼接到数组中元素的实际位置。

$scope.remove = function(project){
    $scope.projects.splice($scope.projects.indexOf(project),1);
}

This way you need to pass to the remove function only the current project.

通过这种方式,您只需要将删除函数传递给当前项目。

<tr ng-repeat="project in projects | orderBy : orderPO : reverse track by $index" ng-click="remove(project)">
    <span class="label" ng-bind="project.statut_name"></span>
</tr>

#1


8  

The simplest solution would be to change your remove function to take in the project instead of the index.

最简单的解决方案是更改您的remove函数,而不是索引。

$scope.remove = function(project){
    for(var i = $scope.projects.length - 1; i >= 0; i--){
        if($scope.projects[i].statut_name == project.statut_name){
            $scope.projects.splice(i,1);
        }
    }
}

Example Plunker: http://plnkr.co/edit/51SNVMQjG3dsmpYI5RyY?p=preview

例子恰好:http://plnkr.co/edit/51SNVMQjG3dsmpYI5RyY?p=preview

#2


21  

It's easier to splice you projects in the actual position of the element in the array using indexOf.

使用indexOf更容易将项目拼接到数组中元素的实际位置。

$scope.remove = function(project){
    $scope.projects.splice($scope.projects.indexOf(project),1);
}

This way you need to pass to the remove function only the current project.

通过这种方式,您只需要将删除函数传递给当前项目。

<tr ng-repeat="project in projects | orderBy : orderPO : reverse track by $index" ng-click="remove(project)">
    <span class="label" ng-bind="project.statut_name"></span>
</tr>