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>

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...