2017-02-23 104 views
0

讓supose我們需要消毒的HTML字符串,我們不能用NG綁定HTML的指令,例如:AngularJS和消毒 - 消毒HTML沒有ngBind指令

<span data-toggle="tooltip" title="Edit {{customer.name}}">Text</span> 

如果我們有特殊字符customer.name這行會打印成html版本,如&eacute;,我們想要é

我與測試:

  • $sce.trustAsHtml(customer.name)
  • $sce.parseAsHtml(customer.name)

但沒有什麼可以 「翻譯」 這個網站。如何做到這一點?

一個簡短的解釋是:如何淨化指令內的html(不在ng-bind-html正文中)。

回答

0

oficial documentation

ngBindHtml使用$ sce.parseAsHtml(綁定表達式)。下面是實際的代碼(略微簡化):

var ngBindHtmlDirective = ['$sce', function($sce) { 
    return function(scope, element, attr) { 
    scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) { 
     element.html(value || ''); 
    }); 
    }; 
}]; 

所以我認爲你需要的是$sce.parseAsHtmlhttps://docs.angularjs.org/api/ng/service/$sce#parseAsHtml)。


如果你無法說服角反正打印HTML,你可以嘗試使用

customer.name.replace(/&eacute;/g, String.fromCharCode(233)); 

你可以找到一些基本的代碼在這裏:http://www.javascripter.net/faq/accentedcharacters.htm

這應該工作,但這絕對不是最好的解決方案。你應該總是使用ng-bind-html

+0

是的,我知道這個解決方案,總是取代wil work。但我的問題是關於使用ngSanitize插件爲了對ng-bind-html之外的每個html char(甚至是不安全的)進行消毒處理,我的意思是你不能像我展示的例子那樣使用指令。還是要謝謝你的幫助。 –

+0

我在askin之前嘗試過這個解決方案。我做了一個'return $ sce.parseAsHtml(value)'函數,但它沒有用,並且在HTML標題=「Edit {{parseCode(customer.name)}}」中。 –

1

它不一定非常複雜。

取而代之,在元素上使用setAttributetextContent(V.S. innerHTML),瀏覽器本身將負責爲您進行消毒。

// To set element attributes 
$span.setAttribute("title", "Edit" + customer.name); 

// To set element content 
$span.textContent = customer.name; 

有關更多詳細信息,請參見the post here。當然,這些都是一次性綁定,所以如果你需要更新,只需在中間扔$watch

+0

是的,它可能是一種解決方案,沒有那麼優雅或有角度的解決方案。它可以在控制器中生成大量的源代碼,具體取決於您必須執行的sanizitations的數量,即使有很多模塊化的功能涉及範圍和手錶。這是我唯一的解決方案,我想我必須接受它。非常感謝你的幫助。 –