2013-02-07 46 views
66

我已經看了很多這個,但我或者我找不到答案,或者我不明白它。一個具體的例子將贏得投票=)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> 

幫助?

我看着這些,等等,但不能使它工作。

回答

80

在這個鏈接看看例子:

http://docs.angularjs.org/api/ngSanitize.$sanitize

基本上,angular有一個指令可以將html插入頁面。你的情況,你可以使用NG綁定,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> 
+1

謝謝!這工作。做了一些編輯:修正了鏈接(所以被怪異地解析),將「ng-bind-html」改爲「ng-bind-html-unsafe」,並給出了一個更完整的例子。 –

+7

它是'n​​g-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

+1

我得到這個錯誤:https://docs.angularjs.org/error/$sce/unsafe in 1。3個 –

13

你也可以使用$sce.trustAsHtml('"<h1>" + str + "</h1>"'),如果你想了解更多細節,請參考$sce