如何在AngularJS服务中使用AngularJS指令?
在我的AngularJS 1.5应用程序中,我有一个在视图中心显示微调器的指令。我希望能够通过服务的方式激活这个旋转器。
因此,例如,可以将服务注入到控制器中,无论何时调用,它都会触发微调器显示在屏幕上。
如何将此指令注入到服务中?
目前,无论我在哪里查看,iI都只能找到关于如何将服务注入到指令中的指令,反之亦然
发布于 2019-03-16 02:50:37
方法是使用$rootScope/$scope event总线:
app.service("dataService", function($rootScope, $http) {
this.get = function() {
$rootScope.$broadcast("dataService.Start");
return $http.get(url).finally(function() {
$rootScope.$broadcast("dataService.Done");
});
};
})在指令中:
app.directive("spinner", function() {
return {
link: postLink,
};
function postLink(scope, elem, attrs) {
scope.$on("dataService.Start", function (event) {
elem[0].startSpinner();
});
scope.$on("dataService.Done", function (event) {
elem[0].stopSpinner();
});
}
});有关更多信息,请参阅AngularJS Developer Guide - Scope Event Propagation
发布于 2019-03-16 08:57:33
你可以安装angular-spinner,然后在你的index.html中包含文件,并在你的应用程序中添加依赖项:
var myapp = angular.module('myapp', ['angularSpinner']);然后,您可以使用自定义指令截获所有http请求,而无需在每次http调用前添加start和在之后停止(代码较少)。
app.directive('usSpinner', ['$http', '$rootScope', function ($http, $rootScope) {
return {
link: function (scope, elm, attrs) {
$rootScope.spinnerActive = false;
scope.isLoading = function () {
return $http.pendingRequests.length > 0;
};
scope.$watch(scope.isLoading, function (loading) {
$rootScope.spinnerActive = loading;
if (loading) {
elm.removeClass('ng-hide');
} else {
elm.addClass('ng-hide');
}
});
}
};
}然后在您的html中,将以下内容添加到body:
<span us-spinner></span>https://stackoverflow.com/questions/55187860
复制相似问题