我试图理解Angular中的工厂和服务概念。在控制器下面,我有以下代码:
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);
};
这段代码能够正常运行。但是当我把$http服务移入工厂时,我无法将数据返回给控制器。
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);
};
});
使用工厂的优势在于什么,既然 $http 甚至可以在控制器下工作?