Reputation: 6124
I am using this code:
$http.get('/api/users').
success(function(data) {
$scope.authors = data;
}).
error(function() {
console.log('API error - config.')
});
And somewhere below (much bellow):
for (var i = 0; i < $scope.authors.length; i++) {
...
};
Sometimes it happens that $scope.authors
are not avaliable yet. Is there any way to solve this?
UPDATE
This is the whole block structure:
// author
$http.get('/api/users').
success(function(data) {
$scope.authors = data;
processAuthors();
}).
error(function() {
console.log('API error - config.')
});
// if updating form
$scope.$on('$routeChangeSuccess', function() {
if($routeParams.id) {
$http.get('/api/offers/' + $routeParams.id).
success(function(data) {
// author
function processAuthors() {
for (var i = 0; i < $scope.authors.length; i++) {
if($scope.authors[i].email == data.author.email) {
$scope.author = $scope.authors[i];
};
};
}
Upvotes: 0
Views: 1258
Reputation: 37701
Yes, it doesn't matter how much below it is - you still need to call it from inside the callback because it's an async call:
function processAuthors() {
for (var i = 0; i < $scope.authors.length; i++) {
...
};
}
And then:
$http.get('/api/users').
success(function(data) {
$scope.authors = data;
processAuthors();
})
I used a function to make it look cleaner, but you can copy your code that depends on the callback inside it.
UPDATE
function processAuthors(data) {
for (var i = 0; i < $scope.authors.length; i++) {
if($scope.authors[i].email == data.author.email) {
$scope.author = $scope.authors[i];
};
};
}
$scope.$on('$routeChangeSuccess', function() {
if($routeParams.id) {
$http.get('/api/offers/' + $routeParams.id).
success(function(data) {
// author
processAuthors(data); // just call it here, define it outside
Upvotes: 1
Reputation: 4044
Put the loop in the succes part:
$http.get('/api/users').
success(function(data) {
$scope.authors = data;
for (var i = 0; i < $scope.authors.length; i++) {
...
};
}).
error(function() {
console.log('API error - config.')
});
Upvotes: 1