0
Today when performing an ajax request for a url containing a json to store within an array, the vector value is only populated within the http method, and out of it from the error, I did 2 console.log
the first works by following around an empty array, follows the code.
myApp.controller('PrincipalController', function($scope, $http) {
$scope.dadosEmail = [];
$http.get('/dados-email.json').success(function(retorno) {
$scope.dadosEmail = retorno;
console.log($scope.dadosEmail);
}).error(function(msg) {
alert('Erro');
});
console.log($scope.dadosEmail);
$scope.ordenaPorNome = function() {
$scope.dadosEmail.sort(function(a, b) {
//Resolve o problema de letras maisculas e minusculas.
a = a.toLowerCase();
b = b.toLowerCase();
if (a.nome > b.nome) {
return 1;
}
if (b.nome > a.nome) {
return -1;
}
return 0;
});
};
});
I would have some way to avoid this problem without involving my function within my AJAX request?
– Leonardo Villela
The most you can do is call a function on
success
and pass to it the return. Within this other function you would define theordenaPorNome
. It’s the same thing in terms of execution flow, only changes the visual organization of the code.– bfavaretto
I thought the code gets a little disorganized, but really you were right, thank you very much :)
– Leonardo Villela
As a matter of fact, so do I. I would not put everything inside the callback, create separate and chained functions, as I explained in the other comment. The code I posted was more to explain the same asynchronous execution flow. Maybe this will help you (although a little too theoretical): http://answall.com/questions/16950/comoreprogram%C3%A7%C3%A3o-ass%C3%Adncrona-funciona-em-javascript
– bfavaretto