我已经为此寻找了很多,但我要么找不到答案,要么不明白。一个具体的例子将赢得投票=)
- 我有一个返回 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>
Help?
Note
我看了这些,但无法使其发挥作用。
- AngularJS:将 HTML 插入视图
- AngularJS $http HTML 解析器
- angularjs - 插入 $compile-d html
- AngularJS 不会在使用 document.write() 插入的 HTML 中执行
- 在 AngularJS 指令中转义 HTML 文本
看一下此链接中的示例:
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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)