首页 文章

AngularJS:从字符串中插入HTML

提问于
浏览
70

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

  • 我有一个返回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"];

那没用 .

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

// 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>

救命?

注意

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

2 回答

  • 87

    看看这个链接中的示例:

    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"];
    

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

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

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

相关问题