【问题标题】:How to activate a spinner directive from a service如何从服务中激活微调器指令
【发布时间】:2019-08-06 20:14:54
【问题描述】:

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

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

因此,例如,可以将服务注入到控制器中,并且无论何时调用,它都会触发微调器显示在屏幕上。

如何将该指令注入到服务中?

目前,无论我在哪里,我都只能找到有关如何将服务注入指令的说明,而不是相反

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-service


    【解决方案1】:

    你可以安装angular-spinner 然后在你的 index.html 中包含文件 并为您的应用添加依赖项:

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

    然后您可以使用自定义指令拦截所有http请求,而无需在每个http调用之前添加开始并在之后停止(更少代码)

    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 中将其添加到正文中:

    <span us-spinner></span>
    

    【讨论】:

      【解决方案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

      【讨论】:

      • 太棒了!非常感谢乔治!
      猜你喜欢
      • 1970-01-01
      • 2020-05-21
      • 1970-01-01
      • 2015-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-24
      • 2020-04-27
      相关资源
      最近更新 更多