如何从服务激活微调器指令

问题描述 投票:0回答:2

如何在AngularJS服务中使用AngularJS指令?

在我的AngularJS 1.5应用程序中,我有一个指令,在视图的中心显示一个微调器。我希望能够通过服务激活这个微调器。

因此,例如,可以将服务注入控制器,并且每当调用时,它将触发微调器显示在屏幕上。

如何将此指令注入服务?

目前,在我看来,iI只能找到关于如何将服务注入指令的说明,而不是相反

angularjs angularjs-directive angularjs-service
2个回答
2
投票

方法是使用$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


0
投票

您可以在index.html中安装qazxsw poi然后包含文件,并为您的应用添加依赖项:

angular-spinner

那么你可以使用自定义指令拦截所有的http请求,而无需在每次http调用之前添加start并在之后停止(代码较少)

var myapp = angular.module('myapp', ['angularSpinner']);

然后在你的html中添加到body:

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');
        }
      });
    }
  };

}
© www.soinside.com 2019 - 2024. All rights reserved.