簡體   English   中英

AngularJS:在編譯之前獲取指令的html內容

[英]AngularJS: Get html content of a directive before compile

我正在創建一個指令,當用戶點擊按鈕時會顯示一個模態:

指令模板:

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

如何在編譯之前獲取指令內部內容並將其替換為模板

嗯..這實際上非常有趣的模式使用模態與這樣的本地內容。

所以,要完成所有你需要的是transclude選項的angular指令。 一篇關於transclude好文章

HTML

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

我們在其中創建模態btn指令和模態內容。 看一下表達式 - 此時我們實際上可以使用當前作用域中的currentScopeData (頁面控制器或其他)。

指令模板

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

只需按一下按鈕即可點擊你的按鈕。

指示

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

所有操作都被評論。 通常我們從指令內提供的transcluded函數中獲取內部內容,並將其設置為范圍。 當用戶點擊showModal按鈕時,我們將內容插入到某個模式持有者中,這可能位於您的html文件中的任何位置。

插入內容后,您需要提供一些顯示功能的模態(可能在modalHolder上添加類或者類似於您的內容)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM