I am trying to understand the concept of factory and service in Angular. I have the following code under the controller
init();
function init(){
$http.post('/services', {
type : 'getSource',
ID : 'TP001'
}).
success(function(data, status) {
updateData(data);
}).
error(function(data, status) {
});
console.log(contentVariable);
};
function updateData(data){
console.log(data);
};
This code works fine. But when i move $http service into factory, i am not able to return data back to controller.
studentApp.factory('studentSessionFactory', function($http){
var factory = {};
factory.getSessions = function(){
$http.post('/services', {
type : 'getSource',
ID : 'TP001'
}).
success(function(data, status) {
return data;
}).
error(function(data, status) {
});
};
return factory;
});
studentApp.controller('studentMenu',function($scope, studentSessionFactory){
$scope.variableName = [];
init();
function init(){
$scope.variableName = studentSessionFactory.getSessions();
console.log($scope.variableName);
};
});
Is there any advantage to using factory, since $http works even under controller
question from:
https://stackoverflow.com/questions/16227644/angularjs-factory-http-service 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…