Assign function return to a variable using angularjs $ promise

1

I have an angled factory that returns json data. Within a controller I invoke the same to get the data, the point is that invoking the same inside the controller object exists only to use a console.log , if you assign it to a variable it becomes empty. Could someone help me?

//Factory
app.factory('dataLoad', function($http, $q) {
     return {
         getContent: function() {
            var deferred = $q.defer();

            $http.get('data-json.php')
            .success(function(data) {
                deferred.resolve(data);
            })
            .error(function() {
                deferred.reject();
            });

            return deferred.promise;
        }
    }
});

Controller:

$scope.node = [];

dataLoad.getContent().then(
    function(data) {
        //Objeto é impresso normalmente
        console.log(data);

        //nulo
        $scope.node = data;
    }
);

console.log($scope.node);
    
asked by anonymous 27.03.2015 / 14:08

1 answer

2

What happens is as follows, your getContent is an asynchronous function, so when you do the console.log ($ scope.node) promise was not yet resolved.

When some assignment is made within a promise it will never be available immediately but only when the promise is resolved.

Try using $ watch to test and see what happens.

EX:

$scope.node = [];

dataLoad.getContent().then(
  function(data) {
      //Objeto é impresso normalmente
      console.log(data);

      //nulo
      $scope.node = data;
  }
);
$scope.$watch('node', function(new_value, old_value){
  console.log($scope.node, new_value, old_value);
})
    
27.03.2015 / 18:04