Angular:在另一个指令中使用指令

时间:2015-12-31 02:15:33

标签: javascript angularjs twitter-bootstrap

我试图在另一个指令中使用指令。具体来说,我有一个模态指令,我想传递一个表格的指令,并将作为模态的主体。

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

我的模态指令:

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;
        }
    };
});

我的模态模板:

<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>

我的表格指示:

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

这是我自己构建的第一个项目,所以我不能100%确定Angular中可用的所有技术。有人能指出我正确的方向吗?感谢

1 个答案:

答案 0 :(得分:1)

你需要的是角度转换:https://docs.angularjs.org/api/ng/directive/ngTransclude

在你的模态指令中,启用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;
        }
    };
});

在模态模板中,将ng-transclude放在您希望插入内容的位置:

<div class="modal-body">
     <ng-transclude></ng-transclude>
</div>
相关问题