I have multiple queries in one controller, that load while the controller is loading (and after I click on some elements)
我在一个控制器中有多个查询,当控制器加载时,这些查询会被加载(在我点击一些元素之后)
var d = $q.defer();
$scope.userOrders = UserOrders.query({id:$routeParams.id}, function(result) {
d.resolve(result);
});
$q.all([d.promise]).then(function(response){
$('#loading').hide();
});
How i can write this only once, not in each controller?
如何只写一次,而不是每个控制器?
1 个解决方案
#1
3
Encapsulate your ajax logic in a service
在服务中封装ajax逻辑
var services = angular.module('myServices', []);
services.factory('AjaxLoader', ['$q', function($q) {
return {
doAjax : function() {
var d = $q.defer();
$scope.userOrders = UserOrders.query({id:$routeParams.id}, function(result) {
d.resolve(result);
});
$q.all([d.promise]);
}
}
});
In your controller.
在你的控制器。
var controllers = angular.module('myControllers',[]);
controllers.controller('Controller', ['AjaxLoader', function(AjaxLoader) {
AjaxLoader.doAjax().then(function() {
$("#loading").hide();
});
}]);
#1
3
Encapsulate your ajax logic in a service
在服务中封装ajax逻辑
var services = angular.module('myServices', []);
services.factory('AjaxLoader', ['$q', function($q) {
return {
doAjax : function() {
var d = $q.defer();
$scope.userOrders = UserOrders.query({id:$routeParams.id}, function(result) {
d.resolve(result);
});
$q.all([d.promise]);
}
}
});
In your controller.
在你的控制器。
var controllers = angular.module('myControllers',[]);
controllers.controller('Controller', ['AjaxLoader', function(AjaxLoader) {
AjaxLoader.doAjax().then(function() {
$("#loading").hide();
});
}]);