Search code examples
angularjsangularjs-directivecontrollers

Can't use a Directive Controller AND Require a Directive Controller (and have them both be available)


So I have a validation directive that should work with ng-form. I need to use their controller but also I need to bind the elements click event to my own controller. If I just use require I can access that form controller, if I just use controller I can access my controller, but if I use both require and controller I only get access to the required controller!

angular.module('app')
  .directive('myValidation', function() {
    return {
      controller: function MyController() {

      },
      link: function($scope, ele, attr, MyCtrl) {
        // All is well
      }
    };
  })
  .directive('myValidationTwo', function() {
    return {
      require: 'form',
      controller: function MyController() {

      },
      link: function($scope, ele, attr, formCtrl) {
        // MyCtrl is not available!
        // formCtrl is not an array of controllers!
      }
    };
  });

Seems like a major oversight if this isn't possible!


Solution

  • You just need to require it specifically.

    angular.module('app')
      .directive('myValidation', function() {
        return {
          controller: function MyController() {
    
          },
          link: function($scope, ele, attr, MyCtrl) {
            // All is well
          }
        };
      })
      .directive('myValidationTwo', function() {
        return {
          require: ['myValidationTwo', 'form'],
          controller: function MyController() {
    
          },
          link: function($scope, ele, attr, ctrl) {
            var MyCtrl = ctrl[0];
            var formCtrl = ctrl[1];
          }
        };
      });