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

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

タイトルは出力されますが、コンテンツは出力されません。それはいくつかのhtmlを持っていると私は次のエラーが表示されます:http://docs.angularjs.org/error/ $ sce:安全ではないですが、次にそれはいくつかのhtmlがあるのでコンテンツを出力することができます{{ revision.content | safe }}またはsmthnに設定します。正しい方法は何ですか?AngularJSテンプレートからhtmlを出力するには?

EDIT:

AngularJSバージョン:1.2

答えて

111

ので、修正はこれです:

http://code.angularjs.org/からangular-sanitize.min.jsが含まれており、あなたのモジュールの中に含まれます:

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

、その後、あなたはng-bind-html

+2

1.4の2年後です。x、この信じられないほど単純な修正はまだ動作します! – xiankai

+0

** $ compile ** – vanduc1102

+5

を使用し、ほぼ3年後の1.5.xで問題が解決しました。 – azuax

2

あなたはどのバージョンを使用していますか? あなたが1.2未満を使用している場合は、私がng-bind-html-unsafeを行うために使用するのと同じ基本的なことをやっng-htmlディレクティブを作成しngBindHtmlUnsafe

3

を試すことができます。しかし、慎重に使用することを強くお勧めします。悪意のある攻撃までサイトを簡単に開くことができます。

.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

編集された構文@paul – scniro

3

を自由に使用している私はそれが古いことを知っていますコントローラ内の$sceを使用して値を信頼することもできます。

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

その後、ng-bind-htmlが動作します。

0

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を注入する必要があります。

1 - バウアー

bower install --save angular-sanitize 

2を使用して - を使用してnpm

npm install --save angular-sanitize 

3 - 手動でダウンロードすることにより

@Xeen answerようcode.angularjs.org path which include all angularJs files categories by version numberからangular-sanitize.jsファイルはディレクティブのOficial angularJs github repository for install angular-sanitize

関連する問題