AngularJS:从字符串插入 HTML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14761724/
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 05:28:58  来源:igfitidea点击:

AngularJS: Insert HTML from a string

htmlstringangularjs

提问by Sir Robert

I've looked a LOT for this, but I either I can't find the answer or I don't understand it. A specific example will win the vote =)

我已经为此寻找了很多,但我要么找不到答案,要么不明白。一个具体的例子将赢得投票=)

  • I have a function that returns an HTML string.
  • I can't change the function.
  • I want the html represented by the string to be inserted into the DOM.
  • I'm happy to use a controller, directive, service, or anything else that works (and is reasonably good practice).
  • Disclaimer: I don't understand $compile well.
  • 我有一个返回 HTML 字符串的函数。
  • 我无法更改功能。
  • 我希望将字符串表示的 html 插入到 DOM 中。
  • 我很高兴使用控制器、指令、服务或任何其他有效的东西(并且是相当好的做法)。
  • 免责声明:我不太了解 $compile 。

Here's what I've tried:

这是我尝试过的:

// My magic HTML string function.
function htmlString (str) {
    return "<h1>" + str + "</h1>";
}

function Ctrl ($scope, $compile) {
  $scope.htmlString = htmlString;
}
Ctrl.$inject = ["$scope", "$compile"];

That didn't work.

那没有用。

I tried it as a directive too:

我也尝试将其作为指令:

// My magic HTML string function.
function htmlString (str) {
    return "<h1>" + str + "</h1>";
}

angular.module("myApp.directives", [])
  .directive("htmlString", function () {
    return {
      restrict: "E",
      scope: { content: "@" },
      template: "{{ htmlStr(content) }}"
    }
  });

  ... and in my HTML ...

  <html-string content="foo"></html-string>

Help?

帮助?

Note

笔记

I looked at these, among others, but couldn't make it work.

我看了这些,其中包括,但无法让它发挥作用。

回答by ganaraj

Have a look at the example in this link :

看看这个链接中的例子:

http://docs.angularjs.org/api/ngSanitize.$sanitize

http://docs.angularjs.org/api/ngSanitize.$sanitize

Basically, angular has a directive to insert html into pages. In your case you can insert the html using the ng-bind-html directive like so :

基本上,angular 有一个将 html 插入页面的指令。在您的情况下,您可以使用 ng-bind-html 指令插入 html,如下所示:

If you already have done all this :

如果您已经完成了所有这些:

// My magic HTML string function.
function htmlString (str) {
    return "<h1>" + str + "</h1>";
}

function Ctrl ($scope) {
  var str = "HELLO!";
  $scope.htmlString = htmlString(str);
}
Ctrl.$inject = ["$scope"];

Then in your html within the scope of that controller, you could

然后在该控制器范围内的 html 中,您可以

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

回答by Java Basketball

you can also use $sce.trustAsHtml('"<h1>" + str + "</h1>"'),if you want to know more detail, please refer to $sce

你也可以使用$sce.trustAsHtml('"<h1>" + str + "</h1>"'),如果你想了解更多细节,请参考$sce