How can I force a directive to work only if it is within a specific directive?

Asked

Viewed 218 times

6

I am trying to make ngPanelHead, ngPanelBody and ngPanelFoot directives need to be within the ngPanel directive, otherwise an error is presented on the console. I tried with require however it is not working. I am using version 1.4.8 of Angularjs.

angular
  .module('app')
  .directive('ngPanel', panel)
  .directive('ngPanelHead', panelHead)
  .directive('ngPanelBody', panelBody)
  .directive('ngPanelFoot', panelFoot);

function panel() {
  var directive = {
    restrict: 'EA',
    replace: true,
    transclude: true,
    template: '<section class="o-panel" ng-transclude></section>'
  }

  return directive;
}

function panelHead() {
  var directive = {
    restrict: 'EA',
    // require: '^ngPanel',
    replace: true,
    transclude: true,
    template: '<header class="o-panel__head" ng-transclude></header>'
  }

  return directive;
}

function panelBody() {
  var directive = {
    restrict: 'EA',
    // require: '^ngPanel',
    replace: true,
    transclude: true,
    template: '<article class="o-panel__body" ng-transclude></article>'
  }

  return directive;
}

function panelFoot() {
  var directive = {
    restrict: 'EA',
    // require: '^ngPanel',
    replace: true,
    transclude: true,
    template: '<footer class="o-panel__foot" ng-transclude></footer>'
  }

  return directive;
}

Thank you!

  • An observation, do not start the name of your directives with ng, the directives Angular has this prefix, so you can accidentally create an existing one. Use your own prefix, eg.: bwPanel

1 answer

2


The parameter require is the correct way to describe dependency requirements in defining Directive.

.directive('subDiretiva', function() {
    return {
        scope: { data: "=" },
        require: ['?^^diretivaPai1', '?^^diretivaPai2'],  // Lista de possíveis diretivas-pai
        template: '<button></button>'
        link: function(scope, elem, attrs, diretivaParenteCtrl) {
              //conteúdo do link aqui            
              };
        },
    }
})
  • Which version of Angular did you do this test? Maybe it is a problem in the version of Angular because in version 1.4.8 it does not work.

  • @Brunowego the Angular documentation test works for me - 'Creating Directives that Communicate', https://docs.angularjs.org/guide/directive

Browser other questions tagged

You are not signed in. Login or sign up in order to post.