【问题标题】:How to remove item from array with filter in AngularJS?如何在AngularJS中使用过滤器从数组中删除项目?
【发布时间】:2014-07-11 15:42:33
【问题描述】:

当我在没有任何过滤器的情况下单击 tr 时,我的函数 array.splice() 有效。数组中的索引顺序正确,因此 array.splice() 有效。

启用过滤器时,数组中的索引不会更新,并且仍然保持相同的顺序。所以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);
    };

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

【问题讨论】:

  • 你不能把项目传递给函数吗?即 ng-click="remove(project)"

标签: javascript arrays angularjs filter angularjs-ng-repeat


【解决方案1】:

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

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

这样你只需要将当前项目传递给remove函数。

<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>

【讨论】:

  • 这应该是公认的答案,这不必遍历数组。
  • 老兄,你是救命稻草,整天都在为此苦苦挣扎
【解决方案2】:

最简单的解决方案是更改您的删除函数以接收项目而不是索引。

$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);
        }
    }
}

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

【讨论】:

    猜你喜欢
    • 2020-02-16
    • 2016-10-30
    • 2017-09-17
    • 2016-02-21
    • 2018-07-20
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 2012-12-24
    相关资源
    最近更新 更多