Search code examples
javascriptangularjsangularjs-service

Loader service with multiple types of targets


Assume this Loader service:
html:

<div class="loader" ng-class="(loader) ? 'show' : 'hide'"></div>


service:

app.service('Loader', function ($rootScope) {
  var _number = 0;
  this.reset = function () {
    $rootScope.loader = false;
    _number = 0;
    return this;
  };

  this.show = function () {
    _number++;
    $rootScope.loader = true;
    return this;
  };

  this.hide = function () {
    _number--;
    if (_number <= 0) {
      $rootScope.loader = false;
    }
    return this;
  };

});

which takes the number of requests in process into account.
Calling Loader.show() before $http requests and Loader.hide() after response received works fine as a loader service but it's just one global loader.
I need to show loader element:

  • inside index.html as global loader for loading content of each view
  • inside buttons for submit events
  • inside popups for loading content of them

I'm looking for a good way to determine which loader element should be shown.


Solution

  • Since I didn't received an answer, I figured out a way myself. I'm publishing it, may be some one need it.
    I separated the loader in two types, a global and a particular witch accepts an element as parameter. and adding a class name "loading-icon", and some states for different types of inputs:

    app.service('Loader', function ($rootScope) {
      var _number = 0;
      this.reset = function () {
      };
    
      this.gloabal = {};
      this.gloabal.show = function () {
      };
      this.gloabal.hide = function () {
      };
    
      this.particular = {};
      // target must be angular element or JS selected DOM element
      this.particular.show = function (target) {
        angular.element(target).addClass('loading');
      };
      this.particular.hide = function (target) {
       angular.element(target).removeClass('loading');
      };
    });
    

    styles :

    .loading-icon:after
    {
      content: '';
      display: inline-block;
      min-width: 20px;
      height: 20px;
      background: ('spinner.gif') no-repeat 0 0;
    }
    

    calling:

    var button = docuemnt.getElementById('submit-button');
    Loader.particular.show(button);
    

    or

    Loader.global.show();