如何在控制器中加载指令

How to load directive in controller?

本文关键字:加载 指令 控制器      更新时间:2023-09-26

基于这个例子悸动指令,如何将自定义指令注入控制器,以便调用函数show()hide()?我无法摆脱以下错误:

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

示例代码:

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

下面是一个使用调度事件以显示/隐藏微调器的示例:

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