Reputation: 95
I created a very simple factory
angular.module('vpmClient')
.factory('DatosFactory', function($http){
var datos = {};
datos.data = [];
datos.getDatos = function(){
$http.post('php/dataHandler.php',{action:"get_datos"}).success(function(data){
datos.data = data;
});
};
datos.getDatos();
return datos;
})
And in the Controller i set the value from "datos.data" to a scope variable
angular.module('vpmClient')
.controller('DatosController', function($http,$scope,DatosFactory){
$scope.datos = DatosFactory.data;
$scope.datoSeleccionado = {};
$scope.getDatos = function(){
console.log(DatosFactory.data);
return DatosFactory.data;
}
$scope.mostrarDato = function(dato){
//$scope.datoSeleccionado = dato;
//Magia
}
});
I need that the value of "scope.datos" updates once the post from the factory ends
Notes: I did a console.log from the factory (inside the success) and it gives me the Object correctly, also, in the controller i created a function to return the factory's value from the browser console and it also works, but when i console.log "scope.datos" it returns an empty object.
Sorry for my bad english
Upvotes: 1
Views: 131
Reputation: 96
Just return the promise from $http to the controller
angular.module('vpmClient').factory('DatosFactory', function($http){
var datos = {};
datos.data = [];
datos.getDatos = function(){
return $http.post('php/dataHandler.php',{action:"get_datos"});
};
return datos;
})
And in the controller you call the service
angular.module('vpmClient').controller('DatosController', function($http,$scope,DatosFactory){
$scope.datos = DatosFactory.data;
$scope.datoSeleccionado = {};
$scope.getDatos = function(){
DatosFactory.getDatos()
.then(function(httpResponse){
console.log(httpResponse.data);
$scope.datoSeleccionado = httpResponse.data;
})
}
});
Upvotes: 2
Reputation: 7360
You need to use the then
keyword:
$scope.getDatos = function() {
DatosFactory.getDatos().then(function(data) {
$scope.datos = data;
});
}
Upvotes: 1