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: /
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/wbebc4cd/1/
Share Improve this question edited Feb 18, 2015 at 12:02 Euphorbium asked Feb 18, 2015 at 11:56 EuphorbiumEuphorbium 1,2775 gold badges19 silver badges35 bronze badges 5- 1 So what is the problem, seems to work? – dfsq Commented Feb 18, 2015 at 11:58
- Sorry, bad link. I've updated the question. – Euphorbium Commented Feb 18, 2015 at 12:03
- First of all the demo doesn't run. I also remend to use Angular 1.3.x. – dfsq Commented Feb 18, 2015 at 12:18
- I know that it does not run. But why? – Euphorbium Commented Feb 18, 2015 at 12:30
- 2 Because you forgot a ma after function expression. jsfiddle/wbebc4cd/4 – dfsq Commented Feb 18, 2015 at 12:35
3 Answers
Reset to default 3As @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/wbebc4cd/5/
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);
}
}
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/0v40rhfb/2/