加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS:从字符串中插入HTML

发布时间:2020-12-17 09:06:45 所属栏目:安全 来源:网络整理
导读:我看了一个LOT这个,但我或者我找不到答案,或者我不明白。一个具体的例子将赢得vote =) 我有一个函数返回一个HTML字符串。 我无法更改功能。 我想将由字符串表示的html插入到DOM中。 我很高兴使用控制器,指令,服务或任何其他工作(并且是相当好的做法)。
我看了一个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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读