Doubt with $ http in AngularJS

2

When I do the get , I load it into an object's $ scope.contacts and I can show it in my View html.

However, I can only access it within my then(function(){}) function, when I leave the part where I called $ http, I can no longer access the $ scope.contatos, where it appears as undefined .

I have seen that even if I create a global variable, if I associate its value with $ scope.contacts within my $ http, I can not access the value of the variable, which will also appear as undefined .

<script type="text/javascript">

    var app = angular.module("myApp",[]);

    app.controller("myCtrl",function($scope,$http){

        $scope.contatos = [];
        $scope.nomes = [];
        var st;

        $http.get("/jsons/contatos.json").then(function(response) {

            console.log("sucesso");
            $scope.contatos = response.data.contatos;
            st = $scope.contatos;

            for(j = 0; j < $scope.contatos.length; j++){
                angular.forEach($scope.contatos[j], function(value,key){                    
                    if(key=="nome"){
                        $scope.nomes.push(value);
                    }                   
                });
            }               
        },function(response){
            console.log("erro");
        });

        console.log($scope.contatos);//aqui ele ja não funciona mais
        console.log(st);//não funciona tambem

    });
</script>

    
asked by anonymous 22.05.2017 / 20:03

1 answer

1

Since the $http.get method is asynchronous, when you run the console.log($scope.contatos); and console.log(st); lines, the $http.get method has not yet returned, for this prints undefined .

    
22.05.2017 / 22:08