wil*_*son 0 javascript arrays foreach angularjs
我有一个从服务中获取的数组,但在控制器中我在forEach()函数中得到一个空值.这是代码.
调节器
这里,'products'和'copyProducts'都是空的.我需要使用'copyProducts'数组到forEach()函数中.
app.controller("controllerApp", function($scope, serviceApp){
var products = serviceApp.query();
$scope.copyProducts = products;
angular.forEach($scope.copyProducts, function(value, key){
console.log("object: "+value);
})
});
Run Code Online (Sandbox Code Playgroud)
服务
app.factory("serviceApp", function($resource){
return $resource("products.json", {}, {
getAll: {
method: "GET",
isArray: true
}
})
})
Run Code Online (Sandbox Code Playgroud)
您的代码是错误的,因为.query()它是异步的,因此它不会立即完成,并且结果未在同一行的下一行准备就绪.因此,一旦完成它的工作,它需要一个回调函数来触发.
serviceApp.query().$promise.then(function(res) {
$scope.products = res;
$scope.copyProducts = res;
angular.forEach($scope.copyProducts, function(item) {
console.log(item)
})
});
Run Code Online (Sandbox Code Playgroud)
替代方案:
serviceApp.query({}, function(res, headers){
//etc
});
Run Code Online (Sandbox Code Playgroud)
顺便说一句,如果你想使用getAll你在资源中定义的方法,那么你就不会使用query()
serviceApp.getAll().$promise.then(function(res){}).....etc
Run Code Online (Sandbox Code Playgroud)