在 angular 重复循环中从 javascript 对象中删除元素

Remove element from javascript object in angular repeat loop

我有以下形式的数据:

$scope.cart={"4": {"cost": 802.85,  "description": "test", "qty": 1},
"5": {"cost": 802.85,  "description": "test", "qty": 1}};

我想遍历此数据并将其显示在删除按钮旁边。如何让按钮从范围中删除行并触发 angular 摘要?所有的教程似乎都是数组中的数据,拼接那个数组,这不符合我的需要。

这是我目前拥有的:http://jsfiddle.net/wbebc4cd/1/

这是删除项目的正确代码。

function CartForm($scope) {
    $scope.cart=[{"id": 1, "cost": 802.85,  "description": "test", "qty": 1}, {"id": 2, "cost": 802.85,  "description": "test", "qty": 1}];


    $scope.removeItem = function(item) {
        var index = $scope.cart.indexOf(item);
        $scope.cart.splice(index, 1);

    }


}

您可以尝试类似的方法:

$scope.removeItem = function(item) { 
    var newCart = {};
    angular.forEach($scope.cart, function(value, key){
        if(value != item)
            newCart[key] = value; 
    });

    $scope.cart = newCart;   
};

JSFiddle:http://jsfiddle.net/0v40rhfb/2/

如@dfsq 所述,您的函数中有错字。

但更根本的是,在地图上重复时,您还应该记住密钥。 (另见 How to use ng-repeat to iterate over map entries in AngularJS

<tr ng:repeat="(key,item) in cart">

然后您可以使用钥匙删除该项目。

<td>[<a href ng:click="removeItem(key)">X</a>]</td>

http://jsfiddle.net/wbebc4cd/5/