質問

AngularJSコントローラーにHTMLフラグメントを作成し、このHTMLをビューに表示することは可能ですか?

これは、一貫性のないJSONブロブをネストされたリストに変えるための要件から来ています id : value ペア。したがって、HTMLはコントローラーに作成されており、現在それを表示しようとしています。

モデルプロパティを作成しましたが、HTMLを印刷するだけではこれをビューでレンダリングすることはできません。


アップデート

問題は、角度を引用符内の文字列としてangularをレンダリングすることから生じるようです。これを回避する方法を見つけようとします。

コントローラーの例:

var SomeController = function () {

    this.customHtml = '<ul><li>render me please</li></ul>';
}

例ビュー:

<div ng:bind="customHtml"></div>

与える:

<div>
    "<ul><li>render me please</li></ul>"
</div>
役に立ちましたか?

解決

Angular 1.xの場合、使用します ng-bind-html HTMLで:

<div ng-bind-html="thisCanBeusedInsideNgBindHtml"></div>

この時点で、 attempting to use an unsafe value in a safe context エラーを使用して、使用する必要があります ngsanitize また $ sce それを解決するために。

$ sce

使用する $sce.trustAsHtml() コントローラーで、HTML文字列を変換します。

 $scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml(someHtmlVar);

ngsanitize

2つのステップがあります:

  1. Angular-Sanitize.min.jsリソースを含める、つまり:
    <script src="lib/angular/angular-sanitize.min.js"></script>

  2. JSファイル(コントローラーまたは通常App.js)に、ngsanitizeを含めます。
    angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'ngSanitize'])

他のヒント

次のようなフィルターを作成することもできます。

var app = angular.module("demoApp", ['ngResource']);

app.filter("trust", ['$sce', function($sce) {
  return function(htmlCode){
    return $sce.trustAsHtml(htmlCode);
  }
}]);

その後、ビューで

<div ng-bind-html="trusted_html_variable | trust"></div>

ノート: :このフィルターは、すべてのHTMLがそれに渡されると信頼しており、ユーザー入力を持つ変数が渡された場合、XSSの脆弱性を提示する可能性があります。

Angular JSは、タグ内でHTMLを表示します

上記のリンクで提供されているソリューションは私のために機能しましたが、このスレッドのオプションはありませんでした。 Angularjsバージョン1.2.9で同じものを探している人のために

これがコピーです:

わかりました、私はこれの解決策を見つけました:

JS:

$scope.renderHtml = function(html_code)
{
    return $sce.trustAsHtml(html_code);
};

HTML:

<p ng-bind-html="renderHtml(value.button)"></p>

編集:

これがセットアップです:

JSファイル:

angular.module('MyModule').controller('MyController', ['$scope', '$http', '$sce',
    function ($scope, $http, $sce) {
        $scope.renderHtml = function (htmlCode) {
            return $sce.trustAsHtml(htmlCode);
        };

        $scope.body = '<div style="width:200px; height:200px; border:1px solid blue;"></div>'; 

    }]);

HTMLファイル:

<div ng-controller="MyController">
    <div ng-bind-html="renderHtml(body)"></div>
</div>

幸いなことに、そのエラーメッセージを回避するために、派手なフィルターや危険な方法は必要ありません。これは、意図した安全な方法でビューでHTMLマークアップを適切に出力するための完全な実装です。

Sanitizeモジュールは、Angularの後に含める必要があります。

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-sanitize.js"></script>

次に、モジュールをロードする必要があります。

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

これにより、コントローラー、ディレクティブなどの文字列にマークアップを含めることができます。

scope.message = "<strong>42</strong> is the <em>answer</em>.";

最後に、テンプレートでは、次のように出力する必要があります。

<p ng-bind-html="message"></p>

予想される出力が生成されます。 42 それは 答え.

私は今日試しました、私が見つけた唯一の方法はこれでした

<div ng-bind-html-unsafe="expression"></div>

ng-bind-html-unsafe もはや機能しません。

これが最短の方法です:

フィルターを作成します:

myApp.filter('unsafe', function($sce) { return $sce.trustAsHtml; });

そしてあなたの見解では:

<div ng-bind-html="customHtml | unsafe"></div>

PSこの方法では、を含める必要はありません ngSanitize モジュール。

HTMLで

<div ng-controller="myAppController as myCtrl">

<div ng-bind-html-unsafe="myCtrl.comment.msg"></div>

また

<div ng-bind-html="myCtrl.comment.msg"></div

コントローラーで

mySceApp.controller("myAppController", function myAppController( $sce) {

this.myCtrl.comment.msg = $sce.trustAsHtml(html);

一緒にも機能します $scope.comment.msg = $sce.trustAsHtml(html);

ng-sanitizeを使用しても、HTMLにngクリックを追加できないことがわかりました。

これを解決するために、指令を追加しました。このような:

app.directive('htmldiv', function($compile, $parse) {
return {
  restrict: 'E',
  link: function(scope, element, attr) {
    scope.$watch(attr.content, function() {
      element.html($parse(attr.content)(scope));
      $compile(element.contents())(scope);
    }, true);
  }
}
});

これがHTMLです:

<htmldiv content="theContent"></htmldiv>

幸運を。

これをフォローしてngbindhtmlを使用してこれを行いました Angular(v1.4)ドキュメント,

<div ng-bind-html="expression"></div> 
and expression can be "<ul><li>render me please</li></ul>"

モジュールの依存関係にngsanitizeを含めるようにしてください。その後、正常に動作するはずです。

Scoped属性を使用することを除いて、BLRBRと非常によく似た別のソリューションは次のとおりです。

angular.module('app')
.directive('renderHtml', ['$compile', function ($compile) {
    return {
      restrict: 'E',
      scope: {
        html: '='
      },
      link: function postLink(scope, element, attrs) {

          function appendHtml() {
              if(scope.html) {
                  var newElement = angular.element(scope.html);
                  $compile(newElement)(scope);
                  element.append(newElement);
              }
          }

          scope.$watch(function() { return scope.html }, appendHtml);
      }
    };
  }]);

その後

<render-html html="htmlAsString"></render-html>

メモして交換できます element.append()element.replaceWith()

新しい問題を使用して、この問題にもう1つのソリューションがあります 属性またはディレクティブ 角度で。

Product-specs.html

 <h4>Specs</h4>
        <ul class="list-unstyled">
          <li>
            <strong>Shine</strong>
            : {{product.shine}}</li>
          <li>
            <strong>Faces</strong>
            : {{product.faces}}</li>
          <li>
            <strong>Rarity</strong>
            : {{product.rarity}}</li>
          <li>
            <strong>Color</strong>
            : {{product.color}}</li>
        </ul>

app.js

 (function() {
var app = angular.module('gemStore', []);    
app.directive("     <div ng-show="tab.isSet(2)" product-specs>", function() {
return {
  restrict: 'E',
  templateUrl: "product-specs.html"
};
});

index.html

 <div>
 <product-specs>  </product-specs>//it will load product-specs.html file here.
 </div>

また

<div  product-specs>//it will add product-specs.html file 

また

<div ng-include="product-description.html"></div>

https://docs.angularjs.org/guide/directive

使用することもできます ng-clude.

<div class="col-sm-9 TabContent_container" ng-include="template/custom.html">
</div>

使用できます 「ng-show」 このテンプレートデータを非表示にするには。

使用する

<div ng-bind-html="customHtml"></div>

angular.module('MyApp', ['ngSanitize']);

そのためには、含める必要があります angular-sanitize.js、たとえば、html-fileで

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular-sanitize.js"></script>

これがこのようなフィルターを作成するソリューションです

.filter('trusted',
   function($sce) {
     return function(ss) {
       return $sce.trustAsHtml(ss)
     };
   }
)

これをフィルターとしてng-bind-htmlに適用します

<div ng-bind-html="code | trusted">

そして、ルーベン・デクロップに感謝します

これがシンプルな(そして安全ではありません) bind-as-html 指令、必要なく ngSanitize:

myModule.directive('bindAsHtml', function () {
    return {
        link: function (scope, element, attributes) {
            element.html(scope.$eval(attributes.bindAsHtml));
        }
    };
});

信頼されていないコンテンツをバインドする場合、これはセキュリティの問題に対して開かれることに注意してください。

SOのように使用:

<div bind-as-html="someHtmlInScope"></div>

Angular 4を使用してテンプレートにHTMLを表示するパイプで作業例。

1.CRATED PIPE ESCEAS-HTML.PIPE.TS

`

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({name : 'keepHtml', pure : false})
export class EscapeHtmlPipe implements PipeTransform{
 constructor(private sanitizer : DomSanitizer){
 }
 transform(content){
  return this.sanitizer.bypassSecurityTrustHtml(content);
 }
}

`2. pipe.module.tsにパイプを登録します

 import {EscapeHtmlPipe} from './components/pipes/escape-html.pipe';
    declarations: [...,EscapeHtmlPipe]
  1. テンプレートで使用します

        <div class="demoPipe"  [innerHtml]="getDivHtml(obj.header) | keepHtml">

  2. getDivHtml() { //can return html as per requirement}

    関連するcomponent.tsファイルにgetDivhtmlの適切な実装を追加してください。

単純な使用 [innerHTML], 、以下のように:

<div [innerHTML]="htmlString"></div>

使用する必要がある前に ng-bind-html...

Angular 7 + Ionic 4では、「[innerhtml]」を使用してHTMLの内容を示すことができます。

<div [innerHTML]="htmlContent"></div>

これがあなたにも役立つことを願っています。ありがとう。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top