0

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

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

4

0 回答 0