javascript - MEAN.JS 堆栈 $http.post().success() 将变量传递到 success() 匿名函数作用域问题

标签 javascript angularjs scope mean-stack

我正在努力完成这项工作:

$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/

相关文章:

r - 使用函数和环境

javascript - 无法从 Angular JS 的 Controller 函数中访问 $scope 变量

c - 定义结构的程序局部指针

javascript - 从 jquery 转换为原型(prototype)

javascript - 基于 bool 值数组在 Vue.js 中绑定(bind)类

javascript - 如何在指令和 Controller 中处理模板 ng-click?

javascript - Angular js 绑定(bind)不起作用

javascript - 在 Javascript 中获取容器的内容,包括父级

javascript - 将数据从 django View 传递到 javascript

javascript - ng-view无法显示数据