AngularJS:在编译前获取指令的html内容

AngularJS: Get html content of a directive before compile

本文关键字:取指令 html 内容 获取 编译 AngularJS      更新时间:2023-09-26

我正在创建一个指令,当用户点击按钮时显示一个模态:

指令模板:

<button ng-click="showModal()">Show Modal</button>

指令的用法:

<modal-btn>
  <div id="modal-content">
    <p>This is the modal content that I want to render in the Modal {{someModel}}</p>
  </div>
</modal-btn>

所以在我编译指令之前,我需要抓取内容,显示按钮,当用户单击按钮时,我显示包含<div id="modal-content">....

的模态

如何在编译指令并将其替换为模板之前获取指令内部内容

嗯…这实际上是一个非常有趣的模式使用modal与本地内容像这样。

所以,要完成所有你需要的是角指令的transclude选项。有一篇关于变性的好文章。

<modal-btn>
  <div class="modal-content">
    Lorem Ipsum Dolor Sit Amet `{{currentScopeData}}`
  </div>
</modal-btn>

我们创建了modal btn指令和其中的模态内容。看一下表达式——此时我们实际上可以使用当前作用域(页面的控制器或其他)中的currentScopeData

<

指令模板/strong>

<button ng-click="showModal()">Show Modal</button>

只是一个像你的一样带有ng-click的按钮。

指令

App.directive('modalBtn', ['Config', function (Config) {
    function link(scope, element, attrs, ctrl, transclude) {
        // Get your modal holder element which may be located anywhere in your application
        var modalHolder = angular.element(document.querySelector('#modal-holder'));
        /**
         * Get transcluded content (which is located inside <modal-btn></modal-btn>)
         *     and set it into scope
         */
        transclude(scope, function(clone, scope) {
            scope.modalContent = clone;
        });
        /**
         * On button click set our transcluded content to the modal holder area 
         */
        scope.showModal = function () {
            modalHolder.empty().append(scope.modalContent);
        }
    }
    return {
        templateUrl: Config.rootPath + 'shared/modal/modal-btn-view.html',
        link: link,
        replace: true,
        // Set transclude option
        transclude: true
    };
}]);

所有操作都有注释。一般来说,我们从指令内部提供的跨包函数中获取内部内容,并将其设置为作用域。当用户点击按钮时,showModal启动,并将我们的内容插入到某个模态holder中,它可能在你的html文件中的任何地方。

插入内容后,您需要提供一些模式显示功能(可能在modalHolder上添加类或类似的东西,这取决于您)。