微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

AngularJS:从字符串中插入HTML

我看了一个LOT这个,但我或者我找不到答案,或者我不明白。一个具体的例子将赢得Vote =)

>我有一个函数返回一个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>

帮帮我?

注意

我看着这些,其他人,但不能使它的工作。

> Insert HTML into view using AngularJS
> AngularJS $http HTML Parser
> angularjs – inserting $compile-d html
> AngularJS doesn’t execute in HTML inserted with document.write()
> Escape HTML text in an AngularJS directive

看看这个链接的例子:

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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐