With ng-bind-html-unsafe removed, how do I inject HTML?

后端 未结 10 1994
不思量自难忘°
不思量自难忘° 2020-11-22 04:06

I\'m trying to use $sanitize provider and the ng-bind-htm-unsafe directive to allow my controller to inject HTML into a DIV.

However, I can

相关标签:
10条回答
  • 2020-11-22 04:39
    1. You need to make sure that sanitize.js is loaded. For example, load it from https://ajax.googleapis.com/ajax/libs/angularjs/[LAST_VERSION]/angular-sanitize.min.js
    2. you need to include ngSanitize module on your app eg: var app = angular.module('myApp', ['ngSanitize']);
    3. you just need to bind with ng-bind-html the original html content. No need to do anything else in your controller. The parsing and conversion is automatically done by the ngBindHtml directive. (Read the How does it work section on this: $sce). So, in your case <div ng-bind-html="preview_data.preview.embed.html"></div> would do the work.
    0 讨论(0)
  • 2020-11-22 04:39

    You do not need to use {{ }} inside of ng-bind-html-unsafe:

    <div ng-bind-html-unsafe="preview_data.preview.embed.html"></div>
    

    Here's an example: http://plnkr.co/edit/R7JmGIo4xcJoBc1v4iki?p=preview

    The {{ }} operator is essentially just a shorthand for ng-bind, so what you were trying amounts to a binding inside a binding, which doesn't work.

    0 讨论(0)
  • 2020-11-22 04:40

    Instead of declaring a function in your scope, as suggested by Alex, you can convert it to a simple filter :

    angular.module('myApp')
        .filter('to_trusted', ['$sce', function($sce){
            return function(text) {
                return $sce.trustAsHtml(text);
            };
        }]);
    

    Then you can use it like this :

    <div ng-bind-html="preview_data.preview.embed.html | to_trusted"></div>
    

    And here is a working example : http://jsfiddle.net/leeroy/6j4Lg/1/

    0 讨论(0)
  • 2020-11-22 04:40

    I've had a similar problem. Still couldn't get content from my markdown files hosted on github.

    After setting up a whitelist (with added github domain) to the $sceDelegateProvider in app.js it worked like a charm.

    Description: Using a whitelist instead of wrapping as trusted if you load content from a different urls.

    Docs: $sceDelegateProvider and ngInclude (for fetching, compiling and including external HTML fragment)

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