Insert HTML into view from AngularJS controller

前端 未结 18 1776
Happy的楠姐
Happy的楠姐 2020-11-21 06:00

Is it possible to create an HTML fragment in an AngularJS controller and have this HTML shown in the view?

This comes from a requirement to turn an

相关标签:
18条回答
  • 2020-11-21 06:24

    Just simple use [innerHTML], like below:

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

    Before you needed to use ng-bind-html...

    0 讨论(0)
  • 2020-11-21 06:25

    You can also create a filter like so:

    var app = angular.module("demoApp", ['ngResource']);
    
    app.filter("trust", ['$sce', function($sce) {
      return function(htmlCode){
        return $sce.trustAsHtml(htmlCode);
      }
    }]);
    

    Then in the view

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

    Note: This filter trusts any and all html passed to it, and could present an XSS vulnerability if variables with user input are passed to it.

    0 讨论(0)
  • 2020-11-21 06:27

    here is the solution make a filter like this

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

    and apply this as a filter to the ng-bind-html like

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

    and thank to Ruben Decrop

    0 讨论(0)
  • 2020-11-21 06:28

    you can also use ng-include.

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

    you can use "ng-show" to show hide this template data.

    0 讨论(0)
  • 2020-11-21 06:34

    I have tried today, the only way I found was this

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

    0 讨论(0)
  • 2020-11-21 06:34

    Just did this using ngBindHtml by following angular(v1.4) docs,

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

    Make sure you include ngSanitize in the module's dependencies. Then it should work fine.

    0 讨论(0)
提交回复
热议问题