简体   繁体   中英

Angular: Directive: How to pass require form AND controller to link function

I have a directive called formNavHandler to handle dirty checking and navigation from page to page. formNavHandler relies on a controller called CoolFormCtrl and a form called coolForm . I want to pass both CoolFormCtrl and coolForm to the link function of formNavHandler

angular.module('cool').directive('formNavHandler', [
  '$log', function($log) {
    return {
      restrict: 'A',
      scope: {
        disabled: '=coolFormDisabled'
      },
      controller: 'CoolFormCtrl',
      require: 'form',
      link: function(scope, elem, attrs, WhatsThis) {
        $log.log(WhatsThis);
        ...
      }
    };
  }
]);

used like so:

<form name="coolForm" form-nav-handler=true cool-form disabled="!CurrentUser.canUpdate">
  ...
</form>

My issue is that I cannot figure out how to pass both form and CoolFormCtrl through the link function.

If I comment out the require:'form' line then WhatsThis = CoolFormCtrl :

With the require:'form' line uncommented WhatsThis = coolForm

And when trying to pass a 5th parameter WhatsThis = coolForm and AndThis = undefined

controller: 'CoolFormCtrl',
require: 'form',
link: function(scope, elem, attrs, WhatsThis, AndThis) {
  $log.log(WhatsThis);
  $log.log(AndThis);

Is there any way to pass both a controller and required form to a directives link function?

Try:

angular.module('cool').directive('formNavHandler', [
   '$log', function($log) {
       return {
          restrict: 'A',
          scope: {
             disabled: '=coolFormDisabled'
          },
          require: ['formNavHandler', 'form'],
          controller: 'CoolFormCtrl',
          link: function(scope, elem, attrs, WhatsThis) {
             $log.log(WhatsThis);
             ...
          }
    };
 }]);

WhatsThis will be an array of controllers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM