在AngularJS中使用工厂/服务的正确方式是什么?
我有这样的基本工厂:在AngularJS中使用工厂/服务的正确方式是什么?,angularjs,Angularjs,我有这样的基本工厂: mModule.factory('ajax_post', ['$http', function(_http) { return{ init: function(jsonData){ var _promise= _http.post('src/php/data.ajax.php', jsonData ,{ headers: {
mModule.factory('ajax_post', ['$http', function(_http) {
return{
init: function(jsonData){
var _promise= _http.post('src/php/data.ajax.php',
jsonData
,{
headers: {
'SOAPActions': 'http://schemas.microsoft.com/sharepoint/soap/UpdateListItems'
}
}
);
return _promise;
}
}]);
在我的控制器中,我称之为:
ajax_post.init($scope.jsonData)
.then(function (result) {
if(result.status == 200){
$scope.isDone = true;
....
}
},
function (error) {
alert(error.message);
});
我想在这里将$scope
用于其他目的,但似乎我只能使用父级(也称$rootScope
)。我只有一个控制器
下面是一些问题:
$scope
是一种良好的做法,还是只有控制器必须使用它(因为根据MVC,我知道$scope
代表当前型号的视图)
退货
,还是他们应该必须退货承诺。然后(…)
进入工厂/服务(意思是:我是否可以将控制器的上述呼叫放入工厂/服务)?或者,唯一正确的方法是创建承诺并从控制器中调用它们控制器
主体中实现上述服务
逻辑.init
代码中传递您的作用域,但随后您将指令与控制器耦合
为什么不在控制器主体中实现上述服务逻辑
控制器不应该知道如何查询microsoft DB。控制员的职责是“准备数据”,而不是获取数据
我可以在一个服务中编写几个相互调用的方法吗
哪种方法可以?从我看到的情况来看,您想要使用q库。像这样:
app.factory('Data', function ($http, $q) {
return {
ajaxItems: function () {
var deferred = $q.defer();
$http({ method: "GET", url: "/Home/GetSearchResults" })
.success(function (data, status, headers, config) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
deferred.reject(data);
});
return deferred.promise;
}
}
});
app.controller('ResultsCtrl', ['$scope', 'Data', function ($scope, Data) {
$scope.get = function () {
$scope.items = Data.ajaxItems();
// q returns a promise and THEN items
$scope.items.then(function (items) {
$scope.items = items;
}, function (status) {
console.log(status);
});
};
}]);
那么是的,您可以,但您可能需要从控制器呼叫服务