Reputation: 968
I am trying to delete values selected by the user in a loop.
for (var i = 0; i < myArray.length; i++) {
MyService.myMapService.delete({id: myArray[i].myId }, myArray[i], function (response) {
if (response.isSuccessful) {
MyService.removeMyValue(myArray[i].myId);
}
})
}
However, I keep receiving the following error
angular.js:13920 TypeError: Cannot read property 'myId' of undefined
Please help!
Upvotes: 1
Views: 26
Reputation: 136134
What happening is, your for loop is getting executed for all MyService.myMapService.delete
function call and your i
is becoming myArray.length
. There after when myMapService.delete
async call completed, it tries to do myArray[i].myId
(where i is array length, then myArray[i]
would be undefined). In this case you have to preserve value of by wrapping it to self executing function.
Code
for (var i = 0; i < myArray.length; i++) {
(function(j) {
MyService.myMapService.delete({
id: myArray[j].myId
}, myArray[j], function(response) {
if (response.isSuccessful) {
MyService.removeMyValue(myArray[j].myId);
}
})
})(i);
}
Upvotes: 1