Search code examples
angularjsangularjs-directiveangularjs-service

How to activate a spinner directive from a service


How does one use an AngularJS directive inside an AngularJS service?

In my AngularJS 1.5 application, I have a directive that displays a spinner in the center of the view. I would like to be able to activate this spinner by way of a service.

So for example, the service could be injected into a controller, and whenever called, it would trigger the spinner to be displayed on the screen.

How can I inject this directive into the service?

Presently, everywhere I look, iI can only find instructions on how to inject services into directives, but not the other way around


Solution

  • The approach is to use the $rootScope/$scope event bus:

     app.service("dataService", function($rootScope, $http) {
         this.get = function() {
             $rootScope.$broadcast("dataService.Start");
             return $http.get(url).finally(function() {
                 $rootScope.$broadcast("dataService.Done");
             });
         };
     })
    

    In the directive:

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

    For more information, see AngularJS Developer Guide - Scope Event Propagation