2

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/

Euphorbium
  • 1,177
  • 5
  • 17
  • 35

3 Answers3

3

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/

Community
  • 1
  • 1
flup
  • 26,937
  • 7
  • 52
  • 74
1

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

    }


}
Dimi Takis
  • 4,924
  • 3
  • 29
  • 41
  • 1
    Yes, you can look up the value in the map. But I think it's clearer to store the key when iterating. – flup Feb 18 '15 at 13:05
0

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/

Mukesh Kalgude
  • 4,814
  • 2
  • 17
  • 32