如何访问Angular Directive中的HTML(Transclusion)

时间:2015-05-12 00:39:38

标签: angularjs angular-ui web-component transclusion angularjs-ng-transclude

我正在使用angular-ui。我试图减少html编码我使用angular指令制作可重用元素。我肯定错过了一些东西。我想做的是:

<modal modal-title="Some Title" button-text="Click Me">Modal Content</modal>

我想要输出模态和按钮,而不是为模态一遍又一遍地添加所有标记,我可以使用这个自定义元素。它似乎工作,除了我不能为我的生活弄清楚如何获取元素内的内容。以下是我正在做的基础知识:

angular.module('app').directive('modal', function () {
    return {
        templateUrl: 'partials/modal.html',
    restrict: 'E',
    controller: 'modalController',
    controllerAs: 'mCtrl',
    transclude: true,
        link: function postLink(scope, element, attrs) {
            scope.buttonText = attrs.buttonText;
            scope.modalTitle = attrs.modalTitle;
        }
    };
}).controller('modalController', function($scope,$modal,$attrs) {
    var _this = this;
    this.buttonText = $attrs.buttonText;
    this.modalTitle = $attrs.modalTitle;

    this.open = function () {

        var modalInstance = $modal.open({
            templateUrl: 'modal-content.html',
            controller: 'ModalInstanceCtrl',
            controllerAs: 'miCtrl',
            resolve: {
                modalTitle: function() { return _this.modalTitle; }
            }
        });

        modalInstance.result.then(function (selectedItem) {
            //something
        }, function () {
            console.info('Modal dismissed at: ' + new Date());
        });
    };

    this.save = function() {
        //something
    };

}).controller('ModalInstanceCtrl', function ($scope, $modalInstance, modalTitle) {
    this.modalValue = 1;
    this.modalTitle = modalTitle;
    this.ok = function () {
        $modalInstance.close(this.modalValue);
    };

    this.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
});

这是模板(partials / modal.html)

<script type="text/ng-template" id="modal-content.html"> 
    <div class="modal-header"> 
        <h3 class="modal-title">{{miCtrl.modalTitle}}</h3> 
    </div> 
    <div class="modal-body"> {{ mCtrl.content }} </div> 
    <div class="modal-footer"> 
        <button class="btn btn-primary" ng-click="miCtrl.ok()">OK</button> 
        <button class="btn btn-warning" ng-click="miCtrl.cancel()">Cancel</button> 
    </div> 
</script>

<button class="btn btn-default" ng-click="mCtrl.open()">{{mCtrl.buttonText}}</button>

如何将元素的内容导入mCtrl.content?其余部分按预期工作,我只是遗漏了一些东西。谢谢!

编辑:我似乎需要使用翻译,所以这就是我想要做的事情:

<div class="modal-body"><ng-transclude></ng-transclude></div>

但是当我打开模态时,我遇到了这种错误:

[ngTransclude:orphan] Illegal use of ngTransclude directive in the template! No parent directive that requires a transclusion found. Element: <ng-transclude>

0 个答案:

没有答案