Ad

Angular: Using A Directive Within Another Directive

- 1 answer

I'm trying to use a directive within another directive. Specifically, I have a modal directive and I want to pass in a directive that is a form and will act as the modal's body.

<modal title='Create Story' action='Create Story' modalid='createStoryModal'>
  <new-story-form></new-story-form>
</modal>

my modal directive:

angular.module('Storyboard').directive('modal', function(){
    return {
        restrict: 'E',
        templateUrl: 'templates/modal.html',
        link: function(scope, element, attrs){
            scope.title = attrs.title;
            scope.action = attrs.action;
            scope.modalId = attrs.modalid;
        }
    };
});

my modal template:

<div class="modal fade" id="{{modalId}}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">{{title}}</h4>
      </div>
      <div class="modal-body">
      <!-- INSERT FORM DIRECTIVE HERE -->
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" ng-click="doSomething()">{{action}}</button>
      </div>
    </div>
  </div>
</div>

my form directive:

angular.module("Storyboard").directive("newStoryForm", function(){
    return {
        restrict: "E",
        template: "<form><input type='text'/></form>",
        link: function(scope, element, attrs){
        }
    };
});

This is the first project I'm building out on my own so I'm not 100% sure of all the techniques available in Angular yet. Can someone point me in the right direction? Thanks

Ad

Answer

what you need is angular transclude: https://docs.angularjs.org/api/ng/directive/ngTransclude

In your modal directive, enable transclude:

angular.module('Storyboard').directive('modal', function(){
    return {
        restrict: 'E',
        transclude: true,
        templateUrl: 'templates/modal.html',
        link: function(scope, element, attrs){
            scope.title = attrs.title;
            scope.action = attrs.action;
            scope.modalId = attrs.modalid;
        }
    };
});

In modal template, put ng-transclude in the place you want the content to be inserted:

<div class="modal-body">
     <ng-transclude></ng-transclude>
</div>
Ad
source: stackoverflow.com
Ad