Reputation: 105
I am trying to replace an element in a list by a new one (data). The list is in my scope as $scope.list.
So I do something like that :
angular.foreach($scope.list, function(element) {
if(element.id === data.id) {
element = data;
console.log(element);
return false;
});
console.log($scope.list);
In the console element is updated but $scope.list remains unchanged.
First I tried to use Array.find() instead of looping the list like this :
$scope.list.filter(x => x.id === data.id)[0] = data;
But I got an error in the console : Invalid left-hand side in assignment.
Do you know why it doesn't change the $scope.list ? I am quite new in AngularJS and JavaScript.
Thanking you in advance,
Upvotes: 2
Views: 1216
Reputation: 820
Try this
$scope.list = $scope.list.map(element => element.id === data.id ? data : element);
A map function is basically a forEach with return - map
Without arrow function and proper if
$scope.list = $scope.list.map(function(element){
if (element.id === data.id){
return data;
}
return element;
});
Upvotes: 2
Reputation: 48968
Use the key
and obj
values exposed to the iterator function:
angular.forEach($scope.list, function(element,key,obj) {
if(element.id === data.id) {
obj[key] = data;
console.log(obj);
return false;
});
For more information, see AngularJS angular.forEach function API Reference.
Upvotes: 0