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/

5
  • 1
    So what is the problem, seems to work? Commented Feb 18, 2015 at 11:58
  • Sorry, bad link. I've updated the question. Commented Feb 18, 2015 at 12:03
  • First of all the demo doesn't run. I also recommend to use Angular 1.3.x. Commented Feb 18, 2015 at 12:18
  • I know that it does not run. But why? Commented Feb 18, 2015 at 12:30
  • 2
    Because you forgot a comma after function expression. jsfiddle.net/wbebc4cd/4 Commented Feb 18, 2015 at 12:35

3 Answers 3

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/

Sign up to request clarification or add additional context in comments.

1 Comment

You help me out of large problem !
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);

    }


}

1 Comment

Yes, you can look up the value in the map. But I think it's clearer to store the key when iterating.
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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.