3

我正在嘗試爲一系列元素的彈出窗口構建動態內容。

使用此指令:

.directive('popover', function($compile){ 
    return { 
     link: function(scope, element, attrs) { 
      // define popover for this element 
      $(element).popover({ 
       html: true, 
       placement: "top", 
       // grab popover content from the next element 
       content: $(element).siblings(".pop-content").html() 
      }); 
     } 
    } 
}); 

的酥料餅的內容包含酥料餅的.pop內容同胞的HTML內容:

<div ng-repeat="o in os"> 
    <a popover href="javascript:;"> 
     show popover 
    </a> 

    <div ng-hide="true" class="pop-content"> 
     {{ 3+4 }} 
    </div> 
</div> 

不幸的是,酥料餅的內容將保持未編譯,原始html,而不是已提供的角模板:

enter image description here

如何將完全呈現的Angular模板(將使用ng-click和ng-hide等指令)注入彈出窗口? 我嘗試撥打$compile((element).siblings(".pop-content").html())(scope)作爲content,但會導致完全空的彈出。

回答

2

我能找到答案。人們需要通過scope作爲參數傳遞給由$compile返回的功能:

.directive('popover', function($compile){ 
    return function(scope, element, attrs) { 

     var tpl = $(element).find('.pop-content').html(); 

     $(element).popover({ 
      html: true, 
      placement: "top", 
      content: $compile(tpl)(scope) 
     }); 

    }; 
}); 

此外,我改變了.popover-content是的element子元素:

<div popover> 
    <div class="popover-content">{{ 3+4 }}</div> 
</div> 
4

你在正確的軌道上使用$ compile;但是,你需要通過$編譯.contents()不是.html()

// grab popover content from the next element 
content: $compile($(element).siblings(".pop-content").contents())(scope) 

JSFiddle

+2

這似乎並不與'NG-repeat'工作:http://jsfiddle.net/exhz2kpr/1 – doque 2014-10-26 21:10:57

+1

@doque好奇。在*擺弄*之後,我認爲這可能只是Angular的一個bug,特別是因爲指令中每個迭代的HTML註釋都仍然生成,儘管沒有實際的HTML與它們一起使用。範圍是完整的,數組是可用的,其他指令似乎在其中發揮很好,但ng-repeat即使沒有引用任何模型也有這種奇怪的行爲:[奇怪的行爲](http://jsfiddle.net/exhz2kpr/2 /) – Christopher 2014-10-26 23:22:30

+1

如果您不需要在popover內容中專門重複ng,而是針對父元素,那麼這應該仍然很好: [ngRepeat container](http://jsfiddle.net/exhz2kpr/3 /) – Christopher 2014-10-26 23:31:35