简体   繁体   中英

Angular.js: how to update one item of an array?

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?

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.

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.

If you use a library with your web app (eg, jQuery) then you can use their IE7/8 support (eg, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM