2

Background: app built in Angular (with routing), Node, Express, MongoDB/Mongoose.

In one controller I have an array of stuff $scope.array=[]; whose items are fetched through an $http request.

I have a routine which modifies one item of the array:

$http.get('/api/update?id='+itemId, ..

Upon success of the get request, I have to update the specific item of $scope.array which has been modified. I know a possible way is to re-fetch the complete array, but seems inefficient.

Can anyone suggest a way to update/substitute only the item which has been modified?

k88074
  • 2,042
  • 5
  • 29
  • 43
  • **Note**: Probably one way would be something like `$scope.array[array.indexOf(modifiedItem)]=updatedItem` but as far as I know `indexOf` does not work in IE browsers. – k88074 Dec 11 '14 at 21:52

3 Answers3

3

You can do something simple like this. You probably already know this.

$scope.array.splice(this.$index,1, updatedItem);

This will replace/update item in array at $index position if you already looping on array with Id check.

0

You could use a strategy like below;

var modified_item_index = arrayIndexOfModifiedItem;
$http.get('').onSuccess(function(result){
    $scope.dataArray[modified_item_index] = result;
});

Essentially use a closure scoped variable to store the array index of the modified item.

Jerome Anthony
  • 7,823
  • 2
  • 40
  • 31
0

If you use a library with your web app (e.g., jQuery) then you can use their IE7/8 support (e.g., jQuery's $.inArray). If not, you can include a simple "polyfill" for IE7/8:

if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(obj, start) { for (var i = (start || 0), j = this.length; i < j; i++) { if (this[i] === obj) { return i; } } return -1; } }

See How to fix Array indexOf() in JavaScript for Internet Explorer browsers for more on this.

Community
  • 1
  • 1
bjfletcher
  • 11,168
  • 4
  • 52
  • 67