2015-12-21 22 views
4

我被這些問題困住了,希望你能指點我正確的方向。如何添加包含jQuery的AngularJS表達式的ajax加載的內容

這裏是fiddle

解釋器

1)我通過Ajax請求得到一些HTML模板,一切正常,這是個什麼樣子:

 <div> 
      <h2 class="splash" ng-bind="view.headline || 'That&#039;s cool'"></h2> 
     </div> 

正如你已經知道,如果view.headline這將輸出這很酷

2)將模板添加到DOM(只是僞代碼)

<div id="thisIsMyTemplatePlaceholder"></div> 
<script> 
var templateFromAjax="<h2 ng-bind=\"view.headline||'That&#039;s cool'\"></h2>"; 
$("#thisIsMyTemplatePlaceholder").html(templateFromAjax); 
</script> 

3)檢查添加HTML可以看到三個「(撇號)在NG-綁定屬性,這將導致我的錯誤

<div id="thisIsMyTemplatePlaceholder"> 
<h2 ng-bind="view.headline||'That's cool'"></h2> 
</div> 

4)這個問題似乎是jQuery的.html()函數,因爲它解碼特殊字符。

jquery is transforming this: 'That&#039;s cool' into 'That's' 
+1

你不應該將jQuery與Angular混合,如果你有一個你想要粘貼到頁面的模板,你應該使用一個指令。因此,要解決您的問題,請使用ng-include粘貼您的模板。 – SoluableNonagon

+0

你能否詳細說明你對該模板的調用是怎樣的?什麼是URL結構? – SoluableNonagon

回答

1

嘗試逃跑兩次。 一個轉義將被刪除爲html() unescapes您的字符串,請參閱here以供參考。

'That\\'s cool'\">That's cool</h2>"; 

現在,當您使用.attr("ng-bind")下面會有結果

view.headline || 'That\'s cool 

這是你想要的效果,或者說只That&#039;s cool工作?

+1

雙逃脫將解決問題 – funktioneer

0

你試過:

<!-- you can just escape the one apostrophe --> 
<h2 ng-bind="view.headline || 'That\'s cool'"></h2> 
+0

這是相同的結果 – funktioneer

1

另一種方式:

首先,模板分離到另一個文件,只是更容易這樣:

myTemplate.html

<h2 ng-bind="view.headline || 'That\'s cool'"></h2> 
<!-- you can just escape the one apostraphe, but really, 
this logic doesn't belong in the html, but rather the 
controller or service which assigns a value to view.headline --> 

然後,可將您的模板:

<div id="thisIsMyTemplatePlaceholder" ng-include="'myTemplate.html'"> </div> 

一個Plunker顯示這方面的工作:

http://plnkr.co/edit/NlzTmlNMQCqHwqVxgCpQ?p=preview

+0

這是工作,但我仍然在尋找一種方式來做到這一點與jQuery。感謝plankr! – funktioneer