As you will see i'm new in AngularJS, JS and in web development at all =) really sorry for that but i try to.
I try to build a massive webform (about 200 different fields) with AngularJS controllers. I need access from controller to root data source. AngularJS team ask do not make Services just for storing data, but i want to make service for load and save data (at start into .json files on a server).
Service:
AppName.factory('MasterData', ['$rootScope', '$http', '$q', '$log',
function($rootScope, $http, $q, $log) {
var responseData;
$http.get('/getdata.php').then(function (response) {
responseData = response.data;
console.log(response.data);
});
return responseData;
}]);
Controller:
AppName.controller('justController', ['$scope', 'MasterData', '$log',
function ($scope, MasterData, $log) {
$scope.data = MasterData.justControllerSectionData;
console.log(MasterData);
}
]);
Controller return undefined. But console.log from service returns the object.
I feel that the problem is too easy, but i can't find how to solve it :(
Also i can't use function like .getData() from controller to service because it ask the data from server each time any controller loads. I have the routes in AngularJS app with 12-14 controllers (full webform divided by sections) and i think it is good to get the data from backend once.
P.S. I think there is problem with promises, but when i try to use code like this:
var defer = $q.defer();
$http.get('/getdata.php').success(function(data){
defer.resolve(data);
});
return defer;
I've got object with resolve, reject and so on. And really can't understand what can i do with it :(
Help me to get the data in controller :)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…