I'm trying to make this work:
$http.post('/route/path', {'username': $scope.threadedUsers[currentIndex].name}).
success(function(data) {
$scope.threadedUsers[currentIndex].ID = data._id;
$scope.threadedUsers[currentIndex].pic = data.profile_picture[0];
}).
error(function(data) {
//error stuff here
});
$scope.threadedUsers is an array of JSON objects being dynamically populated so $scope.threadedUsers[0] = { 'ID': '', 'pic': '', 'messages': [], 'lastTimestamp': '' }
currentIndex is a local variable that refers to which index of the $scope.threadedUsers array that is currently being operated on.
The problem is that inside the success anonymous function, currentIndex is in a new scope. Now I could put currentIndex in $scope, but that seems like bad practice considering this would be the ONLY reason to do that.
Is there anyway to pass in an external value to the success callback function (for the index)? or is the only way to make currentIndex a $scope variable?
You are hitting an extremely common problem/misconception with javascript for/while loops, which are synchronous and asynchronous functions. By the time the asynchronous function, in this case the HTTP post callback executes, the synchronous loop has run to completion and the loop counter variable is already at the final ending value.
Just refactor your code into a helper method that processes a single user.
function updateUser($scope, user) {
$http.post('/route/path', {'username': user.name}).
success(function(data) {
user.ID = data._id;
user.pic = data.profile_picture[0];
}).
error(function(data) {
//error stuff here
});
}
//Here's the code you omitted but is essential to your question
var updateInScope = updateUser.bind(null, $scope);
$scope.threadedUsers.forEach(updateInScope);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments