我已經看了很多這個,但我或者我找不到答案,或者我不明白它。一個具體的例子將贏得投票=)AngularJS:從字符串中插入HTML
- 我有一個函數,返回一個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>
幫助?
注
我看着這些,等等,但不能使它工作。
- AngularJS : Insert HTML into view
- 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
謝謝!這工作。做了一些編輯:修正了鏈接(所以被怪異地解析),將「ng-bind-html」改爲「ng-bind-html-unsafe」,並給出了一個更完整的例子。 –
它是'ng-bind-html-unsafe'直到1.0.8,之後它只是'ng-bind-html',因爲安全和不安全的函數被合併了https://github.com/angular/angular.js/ blob/master/CHANGELOG.md#120-rc1-spooky-giraffe-2013-08-13 – Matthew
我得到這個錯誤:https://docs.angularjs.org/error/$sce/unsafe in 1。3個 –