2013-04-02 254 views
61

HTML這是我的模板如何渲染角模板

<div class="span12"> 
     <ng:view></ng:view> 
</div> 

,這是我的看法模板

<h1>{{ stuff.title}}</h1> 

{{stuff.content }} 

現在我得到content爲html,我想顯示,鑑於。

但我所得到的只是原始的html代碼。我怎麼能渲染爲實際的HTML

+2

哪裏HTML是從哪裏來的?在不同情況下,您需要'ngBindHtmlUnsafe','ngSanitize'或自定義指令。 –

+0

html來自我的數據庫 – user194932147

+1

內容*絕對*可信嗎? –

回答

93

使用 -

<span ng-bind-html="myContent"></span> 

你需要告訴角度不要逃避它。

+0

這是一個錯字 - 他的意思是''。 –

+10

在AngularJS 1.2中API已經改變。 http://stackoverflow.com/questions/18340872/how-do-you-use-sce-trustashtmlstring-to-replicate-ng-bind-html-unsafe-in-angu – amccausl

+2

amccausl拯救了新角度用戶無數小時的調試由於角度「地獄文檔」,ng-bind-html-unsafe已被棄用,請參考上面註釋中的鏈接來解決答案。 – rjm226

2

因此,也許你想擁有這個在您的index.html加載庫,腳本,以期初始化應用:

<html> 
    <body ng-app="yourApp"> 
    <div class="span12"> 
     <div ng-view=""></div> 
    </div> 
    <script src="http://code.angularjs.org/1.2.0-rc.2/angular.js"></script> 
    <script src="script.js"></script> 
    </body> 
</html> 

然後yourView.html可能僅僅是:

<div> 
    <h1>{{ stuff.h1 }}</h1> 
    <p>{{ stuff.content }}</p> 
</div> 

scripts.js可以讓你的控制器的數據$ scoped到它。

angular.module('yourApp') 
    .controller('YourCtrl', function ($scope) { 
     $scope.stuff = { 
     'h1':'Title', 
     'content':"A paragraph..." 
     }; 
    }); 

最後,你必須配置的路由和分配控制器查看它的$範圍(即你的數據對象)

angular.module('yourApp', []) 
.config(function ($routeProvider) { 
    $routeProvider 
    .when('/', { 
     templateUrl: 'views/yourView.html', 
     controller: 'YourCtrl' 
    }); 
}); 

我沒有測試過這一點,對不起,如果有一個但我認爲這是獲取數據的角度方式

+0

如果我想要這種相同的行爲但不依賴於routeProvider會怎麼樣? –

+0

它的使用界面路由器一樣的,只是它的$ stateProvider而不是$ routeProvider和 .STATE( 'yourState',{ 網址: '/', templateUrl: 'yourView.html', 控制器: 'YourCtrl' }); – irth

3

您應該遵循Angular文檔並使用$ sce - $ sce是一種爲AngularJS提供嚴格上下文轉義服務的服務。這裏是一個文檔:http://docs-angularjs-org-dev.appspot.com/api/ng.directive:ngBindHtmlUnsafe

讓我們與asynchroniously加載Eventbrite在線上售票登錄按鈕

在你的控制器的例子:

someAppControllers.controller('SomeCtrl', ['$scope', '$sce', 'eventbriteLogin', 
    function($scope, $sce, eventbriteLogin) { 

    eventbriteLogin.fetchButton(function(data){ 
     $scope.buttonLogin = $sce.trustAsHtml(data); 
    }); 
    }]); 

在你看來只是補充:

<span ng-bind-html="buttonLogin"></span> 

在你服務:

someAppServices.factory('eventbriteLogin', function($resource){ 
    return { 
     fetchButton: function(callback){ 
      Eventbrite.prototype.widget.login({'app_key': 'YOUR_API_KEY'}, function(widget_html){ 
       callback(widget_html); 
      }) 
     } 
    } 
}); 
49

爲此,我使用自定義過濾器。

在我的應用程序:

myApp.filter('rawHtml', ['$sce', function($sce){ 
    return function(val) { 
    return $sce.trustAsHtml(val); 
    }; 
}]); 

然後,在視圖中:

<h1>{{ stuff.title}}</h1> 

<div ng-bind-html="stuff.content | rawHtml"></div> 
+3

這不適合我。仍然變得原始html – chovy

+1

工作對我來說:-) –

+1

這是一個很好的解決方案@Daniel。如果我使用'$ sce.trustAsHtml',我不需要在應用程序模塊中包含'ngSanitize'依賴項?我正在使用Angular 1.3 – Neel