luzny
luzny

Reputation: 2400

How to load directive in controller?

Based on this example throbberDirective, How to inject custom directive to the controller, so that you can call the functions show() hide()? I can't get rid of the following error:

Error: [$injector:unpr] Unknown provider: inputThrobberProvider <- inputThrobber <- landingCtrl

Example code:

var app = angular.module('myapp', ['ngAnimate', 'ui.router', 'templates']);

app.directive('inputThrobber', [function() {
    return {
      restrict: 'A',
      require: 'ngModel',
      controller: function($scope, $element) {
        var inputThrobberCtrl = {
          show: function() {
            $element.addClass('throbbing');
          },
          hide: function() {
            $element.removeClass('throbbing');
          }
        };

        return inputThrobberCtrl;
      }
    };
  }])
  .controller('landingCtrl', ['$scope', 'geolocation', 'inputThrobber', function($scope, geolocation, inputThrobber) {

    // inputThrobber.show()
    geolocation.getAddress().then(function(address) {
        $scope.address = address;
      }).catch(function(err) {
        $scope.error = error;
        $scope.address = '';
      })
      .finally(function() {
        // $inputThrobber.hide()
      });

  }]);

Upvotes: 1

Views: 1392

Answers (1)

Sunil D.
Sunil D.

Reputation: 18193

Here's an example using that dispatches an event to show/hide the spinner:

app.directive('inputThrobber', [function() {
    return {
      restrict: 'A',
      require: 'ngModel',
      controller: function($scope, $element) {
        $scope.$on('startThrobbing', function() {
          $element.addClass('throbbing');
        });
        $scope.$on('stopThrobbing', function() {
          $element.removeClass('throbbing');
        });
      }
    };
  }])

.controller('landingCtrl', ['$scope', 'geolocation', function($scope, geolocation) {
    $scope.$broadcast('startThrobbing');
    geolocation.getAddress().then(function(address) {
        $scope.address = address;
      }).catch(function(err) {
        $scope.error = error;
        $scope.address = '';
      })
      .finally(function() {
        $scope.$broadcast('stopThrobbing');
      });
}]);

Upvotes: 3

Related Questions