eduardouio
eduardouio

Reputation: 13

angular $scope not have value outside de function in angular controller

introduction: I have a problem return value in $http method, i understand how to works $http in $http.post and $http.get method, i can't return value outside the function that call to my factory.

i need use $scope.historias value outside the controller function.

My Angular Factory: First Factory:

mediperbaricaApp.factory('listarTratamientos',['$http','$location','$q', 
                                                function($http, $location, $q){
    var urlBase = host + 'index.php/';
    var service = {};
    console.log('DEBUG = entramos');

    return {
        response : function(response){
            return $http({
                url : (urlBase + 'tratamientos/getTratamientos'),
                method : 'GET' 
            })
        }
    }

}]);

second Factory:

mediperbaricaApp.factory('services', [ '$http' ,'$location', function(
                                                    $http, $location){
  var urlBase = host + 'index.php/';
  var service = {};
  //listado de historias para el autocoplete del form
  service.getHistorias = function(callback){
    console.log('[DEBUG] FAC Listar Historias');
    $http.get(urlBase + 'historias/getHistoria').
    success(function(response){
        return callback(response);
    }).
    error(function(response){
        alert('Lo sentimos!, No se puede recuperar los datos, ' +
                                                      ' intente mas tarde :(');
    })
  };

  return service;
}]);

My Angular Controller Controller, using two last factories, i get same result

mediperbaricaApp.controller('editController',function($scope,listarTratamientos,
                                         $location,$routeParams, services){
    console.log('[DEBUG] CTRL editar tratamientos');
    //use first factory
    $scope.datos = {};
    services.getHistorias(function(response){
        $scope.datos = response.data; // output array with data :)
    })
    //the data no exist in this place.
    console.dir($scope.datos); //$scope.datos lost data :(

    //use second factory
    $scope.midata = {};
    listarTratamientos.response().success(function(data){
        $scope.midata = data;
        console.dir($scope.midata);  // output array with data :)
    });
    //data not exist in this place i dont understand
    console.dir($scope.midata); //$scope.datos lost data :(

Thanks your help!. Att. Eduardo

Upvotes: 1

Views: 749

Answers (1)

Shomz
Shomz

Reputation: 37701

So in this part you have a callback function and you're trying to access the value in the code below it:

services.getHistorias(function(response){
        $scope.datos = response.data; // output array with data :)
    })
    //the data no exist in this place.
    console.dir($scope.datos); //$scope.datos lost data output undefined variable :(

The problem is that the callback function is executed slightly after this code block, so everything you do with that data needs to be called from within that callback, for example:

services.getHistorias(function(response){
        $scope.datos = response.data; // output array with data :)
        myFunction();
    })
...

function myFunction() {
    console.dir($scope.datos); //$scope.datos now available :)
}

The same goes for your other block of code.

Remember this about the callback/async functions: just because a line of code is right below another line of code - it doesn't mean they will execute in that order.


I'll show you two super-simple examples now - a wrong one (like you did), and a good one, using setTimeout to simulate an async call:

The wrong one

var data;

setTimeout(function() {
  data = 'I will not be available!';
}, 100);

alert(data); // undefined


The right one

var data;

setTimeout(function() {
  data = 'Que suerte!';
  showAlert();
}, 100);

function showAlert(){
  alert(data); // all good!
}

Upvotes: 1

Related Questions