【问题标题】:how to remove specific row from list in angularjs如何从angularjs中的列表中删除特定行
【发布时间】:2014-02-19 09:13:11
【问题描述】:

虽然到处搜索,但找不到解决方案 我从列表中删除 CORRECT 行时遇到问题。

例如我有以下数组:

$scope.rows = [{
        "ID": 12,
        "customer": "abc",
        "image": "abc.jpg",
},{
        "ID": 13,
        "customer": "klm",
        "image": "klm.jpg",
},{
        "ID": 14,
        "customer": "xyz",
        "image": "xyz.jpg",
}];     

尝试删除ID = 13的行(ID将从节点服务器接收),代码如下:

        Socket.on('delete', function( ID ) {

            var a = $scope.rows.indexOf(ID);
            $scope.rows.splice(a, 1)

        });

但这不会删除正确的行。

如何指定我的参数以删除正确的行,例如:

remove rows("ID" = ID)

【问题讨论】:

    标签: javascript angularjs array-splice


    【解决方案1】:

    indexOf 在数组中搜索子字符串(而不是在关系数组中)

    试试这个:

    var whatIndex = null;
    angular.forEach($scope.rows, function(cb, index) {
      if (cb.ID === ID) {
         whatIndex = index;
      }
    });
    
    $scope.rows.splice(whatIndex, 1);
    

    【讨论】:

    • 感谢您的回答。这正是我一直在寻找的。现在可以使用了!
    • 这是一个非常优雅的解决方案。谢谢!
    • 这仅在您尝试删除单行时有效。有人有删除多行的解决方案吗?
    【解决方案2】:

    删除当前选定的项目:

    <a href="#" ng-click="remove($index)">Remove an item</a>                     //this one is dynamically generated link using ng-repeat
    
     $scope.remove = function (item) {
            $scope.retrieveddata.splice(item, 1);
        }
    

    您可以使用它的索引删除当前项目。($scope .retreiveddata 是我的数组列表)

    【讨论】:

    • 感谢您的回答。您的解决方案适用于删除按钮。我没有按钮,但我收到一个 ID 可以自动删除行。
    【解决方案3】:

    在这个函数中传递 id

    $scope.deleteCurrentId = function (ID) {
        for (var i = 0; i <= $scope.row.length; i++) {
            if ($scope.row[i].id == ID) {
                $scope.row.splice(i, 1);
            }
        }
    };
    

    $scope.deleteCurrentId = function (ID) {
        angular.forEach($scope.row, function (cb, index) {
            if (cb.id == ID) {
                $scope.row.splice(index, 1);
            }
        });
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-25
      • 1970-01-01
      • 1970-01-01
      • 2017-09-30
      • 1970-01-01
      • 1970-01-01
      • 2019-03-17
      • 1970-01-01
      相关资源
      最近更新 更多