删除 ng-bind-html-unsafe 后,如何注入 HTML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19415394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 14:31:17  来源:igfitidea点击:

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

htmlangularjs

提问by metalaureate

I'm trying to use $sanitizeprovider and the ng-bind-htm-unsafedirective to allow my controller to inject HTML into a DIV.

我正在尝试使用$sanitizeprovider 和ng-bind-htm-unsafe指令来允许我的控制器将 HTML 注入 DIV。

However, I can't get it to work.

但是,我无法让它工作。

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

I discovered that it is because it was removed from AngularJS (thanks).

我发现这是因为它已从 AngularJS 中删除(谢谢)。

But without ng-bind-html-unsafe, I get this error:

但是没有ng-bind-html-unsafe,我收到此错误:

http://errors.angularjs.org/undefined/$sce/unsafe

http://errors.angularjs.org/undefined/$sce/unsafe

采纳答案by p.matsinopoulos

  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 ngSanitizemodule on your appeg: var app = angular.module('myApp', ['ngSanitize']);
  3. you just need to bind with ng-bind-htmlthe original htmlcontent. No need to do anything else in your controller. The parsing and conversion is automatically done by the ngBindHtmldirective. (Read the How does it worksection on this: $sce). So, in your case <div ng-bind-html="preview_data.preview.embed.html"></div>would do the work.
  1. 您需要确保已加载 sanitize.js。例如,从https://ajax.googleapis.com/ajax/libs/angularjs/[LAST_VERSION]/angular-sanitize.min.js加载它
  2. 你需要ngSanitize在你的appeg中包含模块:var app = angular.module('myApp', ['ngSanitize']);
  3. 您只需要与ng-bind-html原始html内容绑定即可。无需在控制器中执行任何其他操作。解析和转换由ngBindHtml指令自动完成。(阅读How does it work关于此的部分:$sce)。所以,在你的情况下<div ng-bind-html="preview_data.preview.embed.html"></div>会做这项工作。

回答by Leeroy Brun

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

正如 Alex 所建议的那样,您可以将其转换为一个简单的过滤器,而不是在您的范围内声明一个函数:

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/

这是一个工作示例:http: //jsfiddle.net/leeroy/6j4Lg/1/

回答by ijprest

You indicated that you're using Angular 1.2.0... as one of the other comments indicated, ng-bind-html-unsafehas been deprecated.

您表示您正在使用 Angular 1.2.0... 作为其他评论之一,ng-bind-html-unsafe已被弃用。

Instead, you'll want to do something like this:

相反,你会想要做这样的事情:

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

In your controller, inject the $sceservice, and mark the HTML as "trusted":

在您的控制器中,注入$sce服务,并将 HTML 标记为“受信任”:

myApp.controller('myCtrl', ['$scope', '$sce', function($scope, $sce) {
  // ...
  $scope.preview_data.preview.embed.htmlSafe = 
     $sce.trustAsHtml(preview_data.preview.embed.html);
}

Note that you'll want to be using 1.2.0-rc3 or newer. (They fixed a bugin rc3 that prevented "watchers" from working properly on trusted HTML.)

请注意,您需要使用 1.2.0-rc3 或更新版本。(他们修复rc3 中的一个错误该错误阻止“观察者”在受信任的 HTML 上正常工作。)

回答by Alex

For me, the simplest and most flexible solution is:

对我来说,最简单、最灵活的解决方案是:

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

And add function to your controller:

并向您的控制器添加功能:

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

Don't forget add $sceto your controller's initialization.

不要忘记添加$sce到控制器的初始化中。

回答by Paul

The best solution to this in my opinion is this:

在我看来,最好的解决方案是这样的:

  1. Create a custom filter which can be in a common.module.js file for example - used through out your app:

    var app = angular.module('common.module', []);
    
    // html filter (render text as html)
    app.filter('html', ['$sce', function ($sce) { 
        return function (text) {
            return $sce.trustAsHtml(text);
        };    
    }])
    
  2. Usage:

    <span ng-bind-html="yourDataValue | html"></span>
    
  1. 创建一个自定义过滤器,例如可以在 common.module.js 文件中 - 在您的应用程序中使用:

    var app = angular.module('common.module', []);
    
    // html filter (render text as html)
    app.filter('html', ['$sce', function ($sce) { 
        return function (text) {
            return $sce.trustAsHtml(text);
        };    
    }])
    
  2. 用法:

    <span ng-bind-html="yourDataValue | html"></span>
    

Now - I don't see why the directive ng-bind-htmldoes not trustAsHtmlas part of its function - seems a bit daft to me that it doesn't

现在 - 我不明白为什么指令ng-bind-htmltrustAsHtml作为其功能的一部分 - 对我来说似乎有点愚蠢,它没有

Anyway - that's the way I do it - 67% of the time, it works ever time.

无论如何 - 这就是我这样做的方式 - 67%的时间,它始终有效。

回答by Jason Goemaat

You can create your own simple unsafe html binding, of course if you use user input it could be a security risk.

您可以创建自己的简单的不安全 html 绑定,当然,如果您使用用户输入,则可能存在安全风险。

App.directive('simpleHtml', function() {
  return function(scope, element, attr) {
    scope.$watch(attr.simpleHtml, function (value) {
      element.html(scope.$eval(attr.simpleHtml));
    })
  };
})

回答by ksimons

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

您不需要在 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

这是一个例子: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.

{{ }} 运算符本质上只是 ng-bind 的简写,因此您尝试的操作相当于绑定内部的绑定,但这是行不通的。

回答by Lahmizzar

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

我遇到了类似的问题。仍然无法从我托管在 github 上的降价文件中获取内容。

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

在 app.js 中为 $sceDelegateProvider 设置白名单(添加了 github 域)后,它就像一个魅力。

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

描述:如果您从不同的 url 加载内容,则使用白名单而不是包装为受信任的。

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

文档:$sceDelegateProviderngInclude(用于获取、编译和包含外部 HTML 片段)

回答by Sean Fahey

Strict Contextual Escaping can be disabled entirely, allowing you to inject html using ng-html-bind. This is an unsafe option, but helpful when testing.

可以完全禁用严格上下文转义,允许您使用ng-html-bind. 这是一个不安全的选项,但在测试时很有帮助。

Example from the AngularJS documentation on $sce:

AngularJS 文档中的$sce示例:

angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  // Completely disable SCE.  For demonstration purposes only!
  // Do not use in new projects.
  $sceProvider.enabled(false);
});

Attaching the above config section to your app will allow you inject html into ng-html-bind, but as the doc remarks:

将上述配置部分附加到您的应用程序将允许您将 html 注入ng-html-bind,但正如文档所述:

SCE gives you a lot of security benefits for little coding overhead. It will be much harder to take an SCE disabled application and either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE for cases where you have a lot of existing code that was written before SCE was introduced and you're migrating them a module at a time.

SCE 以很少的编码开销为您提供了很多安全优势。获取禁用 SCE 的应用程序并自行保护它或在稍后阶段启用 SCE 会困难得多。如果您有很多在引入 SCE 之前编写的现有代码,并且一次将它们迁移到一个模块,则禁用 SCE 可能是有意义的。

回答by BotanMan

You can use filter like this

您可以像这样使用过滤器

angular.module('app').filter('trustAs', ['$sce', 
    function($sce) {
        return function (input, type) {
            if (typeof input === "string") {
                return $sce.trustAs(type || 'html', input);
            }
            console.log("trustAs filter. Error. input isn't a string");
            return "";
        };
    }
]);

usage

用法

<div ng-bind-html="myData | trustAs"></div>

it can be used for other resource types, for example source link for iframes and other types declared here

它可以用于其他资源类型,例如 iframe 的源链接和此处声明的其他类型