2013-11-04 48 views
28
<h1>{{ revision.title }}</h1> 

<div ng-bind-html="revision.content"></div> 

標題輸出不錯,但內容 - 沒有。它有它的一些html和我得到以下錯誤:Attempting to use an unsafe value in a safe context.它被描述爲這樣:http://docs.angularjs.org/error/ $ SCE:不安全的,這很好,但後來我怎麼能輸出的內容,將有它的一些HTML,所以我必須將其設置爲{{ revision.content | safe }}或smthn。什麼是正確的方法?如何通過AngularJS模板輸出html?

編輯:

AngularJS版本:1.2

回答

111

所以解決方法是這樣的:

包括http://code.angularjs.org/angular-sanitize.min.js,包括它的模塊中:

var app = angular.module('app', ['ngSanitize']); 

,然後你可以自由地使用ng-bind-html

+2

兩年後的1.4。x,這個看似簡單的修復仍然有效! – xiankai

+0

它解決了我的問題,當我使用** $ compile ** – vanduc1102

+5

和近1.5年後的1.5.x也可以 – azuax

2

什麼版本您使用的? 如果使用低於1.2,你可以嘗試ngBindHtmlUnsafe

3

我創建了一個ng-html指令,這是否ng-bind-html-unsafe用來做同樣的基本的東西。不過,我強烈建議你只能謹慎使用它。它可以很容易地打開您的網站直到惡意攻擊。所以,知道自己在做什麼,你實現它之前:

.directive('ngHtml', ['$compile', function($compile) { 
    return function(scope, elem, attrs) { 
     if(attrs.ngHtml){ 
      elem.html(scope.$eval(attrs.ngHtml)); 
      $compile(elem.contents())(scope); 
     } 
     scope.$watch(attrs.ngHtml, function(newValue, oldValue) { 
      if (newValue && newValue !== oldValue) { 
       elem.html(newValue); 
       $compile(elem.contents())(scope); 
      } 
     }); 
    }; 
}]); 

然後您可以使用它作爲:

<div ng-html="revision.content"></div> 

希望有所幫助。

+1

感謝指令安裝ngSanitize模塊的偉大工程!只是最後一行缺少結束] - 應該是'}]);' – paul

+0

編輯語法@保羅 – scniro

3

我知道這是一個老的問題,但你也可以信任你的控制器使用$sce值:

$scope.revision.content = $sce.trustAsHtml($scope.revision.content); 

之後,ng-bind-html會工作。根據Official AngularJs Doc about ngBindHtml你必須注入ngSanitize到您的應用程序依賴

Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default, the resulting HTML content will be sanitized using the $sanitize service. To utilize this functionality, ensure that $sanitize is available, for example, by including ngSanitize in your module's dependencies (not in core Angular). In order to use ngSanitize in your module's dependencies, you need to include "angular-sanitize.js" in your application.

然後你就可以有辦法安裝ngSanitize模塊