Use variable $ scope

1

I have a function where I obtain parameters from an API via $ http.post, the parameters that return are saved and printed inside the same request, however when I use them out the variable appears empty.

$scope.gama = {};

factoryGamas.buscarGama_x_nombre( objCons.gama ).then(function(reponse){
    $scope.gama = reponse.data.fields;
});

If I do a console.log ($ scope.gama) the result is empty, or in this case {}

But when doing a console.log inside the function if I return the values.

factoryGamas.buscarGama_x_nombre( objCons.gama ).then(function(reponse){
        $scope.gama = reponse.data.fields;
        console.log( $scope.gama );
    });

How could I use the variable outside the function if I am already using it within the $ scope?

Thanks!

    
asked by jmrtn 28.11.2017 в 18:31
source

1 answer

1

What is inside the then () is handled in a different scope. The $ scope you are assigning the response data is not the same. A simple way to avoid this problem is by creating a variable to save the scope.

var self = $scope;
factoryGamas.buscarGama_x_nombre( objCons.gama ).then(function(reponse){
    self.gama = reponse.data.fields;
});

This way you are assigning the response to a variable in the external scope and it is already available to be used.

    
answered by 28.11.2017 / 18:44
source