2

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,

1
  • 1
    element=data is only changing a variable in memory. You need to change the value of the array element at the index where the id's match Commented Nov 17, 2018 at 20:58

2 Answers 2

2

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;
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. It works pretty good now ! I assume it's better to do this way or, as someone said above, to loop and then update the list at the correct index ?
I think this is the best way as it is a functional programming way. I think for loops should be prohibited :D
0

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.

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.