0

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

0

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Hey thanks it worked. I'll have to look into transclusion a bit more

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.