Doubt ajax request with angular js

0

Now when executing an ajax request for a url containing a json to store inside a vector, the value of the vector is only populated inside the http method, and outside of the error, I made 2 console.log following an empty array, follow 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;
        });    
    };
});
    
asked by anonymous 23.01.2015 / 02:25

1 answer

2

You need to put all the code that depends on the result of the request within the callback of success. In the position it is in, this code executes before the result is available, as the HTTP request is done asynchronously.

Your code should look like this:

myApp.controller('PrincipalController', function($scope, $http) {

    $scope.dadosEmail = [];

    $http.get('/dados-email.json').success(function(retorno) {
         $scope.dadosEmail = retorno; 

         $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;
             });    
         };
    }).error(function(msg) {
        alert('Erro');    
    });
});

As the $scope.ordenaPorNome function will only be defined after the request response arrives, you also need to be careful not to call it before it exists.

    
23.01.2015 / 02:30