AngularJS:从字符串插入HTML

2eafrhcq  于 5个月前  发布在  Angular
关注(0)|答案(2)|浏览(41)

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

  • 我有一个返回HTML字符串的函数。
  • 我不能改变功能。
  • 我想把字符串表示的html插入到DOM中。
  • 我很乐意使用控制器、指令、服务或其他任何有效的东西(并且是相当好的实践)。
  • 免责声明:我不太理解$compile。

我是这么做的:

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


帮忙?

  • 注意 *

我看了看这些,还有其他的,但是不能让它工作。

ao218c7q

ao218c7q1#

看看这个链接中的例子:
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>

wtzytmuj

wtzytmuj2#

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

相关问题