作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何将增量值传递给 $http.get 函数。请参阅下面的代码片段:
for($scope.index=0 ; $scope.index < 5 ; $scope.index++)
{
$http.get('/api/post', {params: { id: $scope.userActivity[$scope.index].post }})
.success(function(res){
console.log('The value for index is: ' + $scope.userActivity[$scope.index]);
})
.error(function(data, status){
console.log(data);
});
}
})
我收到“索引的值是:未定义”这让我抓狂!
谢谢
最佳答案
问题是,当您的第一个(实际上是所有)成功
回调触发时,$scope.index
将具有值 5
大概在 $scope.userActivity
数组的范围之外。
解决这个问题的一种方法是使用 IIFE
for($scope.index=0 ; $scope.index < 5 ; $scope.index++)
{
(function(i){
$http.get('/api/post', {params: { id: $scope.userActivity[i].post }})
.success(function(res){
console.log('The value for index is: ' + $scope.userActivity[i]);
})
.error(function(data, status){
console.log(data);
});
}
})
})($scope.index);
}
另一个 StackOverflow Q/A 将为您提供更深入的细节:JavaScript closure inside loops – simple practical example
关于javascript - 如何将增量索引值传递给 $http.get,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40222482/
我是一名优秀的程序员,十分优秀!