AngularJS:从字符串中插入HTML

Sir*_*ert 73 html string angularjs

我看了很多,但我要么找不到答案,要么我不明白.一个具体的例子将赢得投票=)

  • 我有一个返回HTML字符串的函数.
  • 我不能改变这个功能.
  • 我希望将字符串表示的html插入到DOM中.
  • 我很高兴使用控制器,指令,服务或其他任何有效的方法(并且是相当不错的做法).
  • 免责声明:我不理解$编译好.

这是我尝试过的:

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

function Ctrl ($scope, $compile) {
  $scope.htmlString = htmlString;
}
Ctrl.$inject = ["$scope", "$compile"];
Run Code Online (Sandbox Code Playgroud)

那没用.

我也试过它作为一个指令:

// 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>
Run Code Online (Sandbox Code Playgroud)

救命?

注意

除了别的以外,我看过这些,但无法使它发挥作用.

gan*_*raj 89

看看这个链接中的示例:

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

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

如果你已经完成了这一切:

// 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"];
Run Code Online (Sandbox Code Playgroud)

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

<div ng-bind-html="htmlString"></div>
Run Code Online (Sandbox Code Playgroud)

  • @AakilFernandes,我不得不添加```ngSanitize```到我的```NG-收口html```工作主要模块. (9认同)
  • 它是`ng-bind-html-unsafe`直到1.0.8,之后它只是`ng-bind-html`因为安全和不安全的函数被合并了https://github.com/angular/angular.js/blob /master/CHANGELOG.md#120-rc1-spooky-giraffe-2013-08-13 (8认同)

Jav*_*all 15

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