1
I have an angle.Factory that returns data from json. Within a controller I invoke the same to take the data, the point is that by invoking the same within the controller the object exists only if you use a console.log
, If you set a variable, it is 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);
I used the $watch and the data is now present. In case I always have to use watch to get the data?
– user2259865
If you have print in the view {{Node}} it will work without the $watch because the angular makes a bind of this property, the issue is that the console log. is executed before Promise is resolved. What you really need to do?
– Daniel
Daniel, I need to assign the return to a variable, because I will call Factory N times and with the return I will call another method to display the data.
– user2259865
I believe that the correct then would be to call your method within the .then instead of assigning to a variable to then call the method.
– Daniel
Thanks Daniel. Subject solved with the code you sent.
– user2259865