質問

I'm trying to learn from the angular-ui code. I see that the btnRadio directive requires itself. I understand that directives may require controllers and then access them as an array in the fourth parameter of the link function. I don't understand why a directive would require itself though.

.directive('btnRadio', function () {
  return {
    require: ['btnRadio', 'ngModel'],
    controller: 'ButtonsController',
    link: function (scope, element, attrs, ctrls) {
      var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];
      ...

https://github.com/angular-ui/bootstrap/blob/master/src/buttons/buttons.js#L15

This is just requiring its own controller, right? What is the purpose of this, or what problem is it solving?

役に立ちましたか?

解決 2

The structure of that application is very odd to me. It seems that they could better define it like this:

angular.module('ui.bootstrap')
  .controller('ButtonsController', function($scope, buttonConfig) {
    $scope.activeClass = buttonConfig.activeClass || 'active';
    $scope.toggleEvent = buttonConfig.toggleEvent || 'click';
  })
  .directive('btnRadio', function() {
    return {
      require: 'ngModel',
      controller: 'ButtonsController',
      link: function(scope, elem, attrs, ngModel) {
        // These are now available here in the link function
        scope.activeClass;
        scope.toggleEvent;
        // ... other functionality
      }
    }
  });

However, @Jeff is right. They do it so that they will have access to the ButtonsController. If you look further down in the code, they're just using it to access the activeClass and toggleEvent attributes.

The only reason I can think for doing it the way that it currently is done would be to avoid generating an isolate scope on the directive. An isolate scope might interfere with code that is external to this library.

他のヒント

I believe it's to retrieve the controller inside the link function.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top