在第一次加载时,我希望应用程序在第一次加载时从X个http请求(X基于水果中元素的数量)异步检索数据,并更新一条指令,该指令显示已检索到多少个项目。检索所有项目后,将触发一个事件,导致该指令/ dom元素被隐藏。
用angular做到这一点的最佳方法是什么?以下是我对服务,控制器和指令的职责的看法。这是正确的吗?还是应该有其他/更好的方法来做到这一点?
APP.service('myService', function($http) {
this.fruits = ['Apple', 'Bannana', 'Pear', 'Orange'];
this.processedFruit = [];
});
APP.controller('myController', ['$scope', '$http', 'myService', function($scope,$http) {
$scope.$emit('LOAD');
// Should the following be in the service instead of the controller?
for(var i = 0; i < myService.fruits; i++) {
$http.get('someurl/'+fruits[i]).success(function(response) {
myService.processedFruit.push(response);
// Somehow tell the "statusofloading" directive to update its (Completed $http Requests)?
});
}
// Once all requests are finished $scope.$emit('UNLOAD') somehow to the directive?;
}]);
APP.directive('statusofloading', function() {
return {
scope:true,
restrict:'E',
link: function($scope,e,a) {
//Completed $http Requests
$scope.completeRequests = 0;
// Total $http Requests
$scope.totalRequests = // Get the number from the service somehow from (length of this.fruits);
$scope.$on('LOAD', function(){$scope.loading=true});
$scope.$on('UNLOAD', function(){$scope.loading=false});
},
replace: true,
template:"<h1>({{completedRequests}}) / ({{totalRequests}}) </h1>"
}
})
$ emit使用第二个参数,您可以在其中传递任何所需的参数。
$scope.$emit('LOAD',{totalRequests: myService.fruits});
然后在您的指令中:
$scope.$on('LOAD', function(args){
$scope.loading=true;
$scope.totalRequests = args.totalRequests;
});
然后,您可以告诉指令何时完成请求,并且知道何时完成所有操作,并且需要隐藏自身。确保将失败的请求和成功的请求通知给指令。
另请参阅角度忙碌,这是解决该问题的另一种通用方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句