我正在努力完成这项工作:
$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 是动态填充的 JSON 对象数组 所以 $scope.threadedUsers[0] = { 'ID': '', 'pic': '', 'messages': [], 'lastTimestamp': '' }
currentIndex 是一个局部变量,表示当前正在操作的 $scope.threadedUsers 数组的索引。
问题在于,在 success 匿名函数内,currentIndex 位于新的作用域中。现在我可以将 currentIndex 放入 $scope 中,但这似乎是不好的做法,因为这是这样做的唯一原因。
是否有办法将外部值传递给成功回调函数(用于索引)?或者是使 currentIndex 成为 $scope 变量的唯一方法?
最佳答案
您遇到了关于 javascript for/while 循环的一个极其常见的问题/误解,它们是同步函数和异步函数。当异步函数(在本例中是 HTTP post 回调)执行时,同步循环已运行完成,并且循环计数器变量已达到最终结束值。
只需将代码重构为处理单个用户的辅助方法即可。
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);
关于javascript - MEAN.JS 堆栈 $http.post().success() 将变量传递到 success() 匿名函数作用域问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25095606/