Euphorbium
Euphorbium

Reputation: 1277

Remove element from javascript object in angular repeat loop

I have data in the following form:

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

I'd like to loop through this data and display it alongside remove button. How can I make the button remove the row from the scope and also trigger angular digest? All of the tutorials seem to have the data in array, and splicing that array, this does not fit my needs.

This is what I have so far: http://jsfiddle.net/wbebc4cd/1/

Upvotes: 2

Views: 8763

Answers (3)

Nathan Heskia
Nathan Heskia

Reputation: 17

You could try something like:

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

Upvotes: 0

flup
flup

Reputation: 27104

As @dfsq mentioned, you have a typo in your function.

But more fundamentally, when repeating over the map, you should also remember the key. (See also How to use ng-repeat to iterate over map entries in AngularJS)

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

Then you can use the key to remove the item.

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

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

Upvotes: 3

Dimi Takis
Dimi Takis

Reputation: 4939

here is the correct code for getting the item removed.

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

    }


}

Upvotes: 1

Related Questions