2015-02-23 52 views
0

我正在嘗試渲染指令,並使用AngularJS將它正確顯示在HTML中。我有一項服務,負責向用戶顯示警告消息。每個控制器我可以調用此服務並設置一條消息,我想要顯示。現在,其中一條消息應該包含鏈接。但是,當我使用Ionic框架時,我需要使用一個指令來完成。使用AngularJS在html字符串中渲染指令

HTML: 
<div class="bar bar-loading bar-assertive top-bar"> 
    | {{ message }} 
</div> 

JS: 
$scope.message = "Please visit this link: <a ui-sref='app.settings.profile-show'>Open me.</a>" 

但是,消息沒有正確輸出在html中。如果我使用以下我得到的HTML,但該指令不計算:

<div class="bar bar-loading bar-assertive top-bar" ng-bind-html="message"></div> 

我會如何做到這樣?謝謝。

+0

你能告訴我們指令碼嗎?也許你錯過了transclude? – Kinnza 2015-02-23 13:59:40

+0

我認爲Ionic從ui.router包中獲取它。它的文檔可以在這裏找到:https://github.com/angular-ui/ui-router#nested-states--views。希望有所幫助。 – Hendrik 2015-02-23 14:08:26

+0

你使用離子框架角度支持http://ionicframework.com/docs/api/?你試圖使用哪個組件? – Kinnza 2015-02-23 14:15:51

回答

1

我不確定Ionic框架,但這是我呈現HTML內容的方式。使用$ sce.trustAsHtml(html)將文本呈現爲html。你的代碼看起來像這樣。

// ... 
app.controller('yourCtrl', function ($scope,$sce) { 
    $scope.message = "Please visit this link: <a ui sref='app.settings.profile-show'>Open me.</a>"; 
    $scope.renderHTML = function(html_code){ 
     return $sce.trustAsHtml(html_code); 
    }; 
} 

HTML

<div class="bar bar-loading bar-assertive top-bar" ng-bind-html="renderHTML(message)"></div> 
<!-- or this way? --> 
<div class="bar bar-loading bar-assertive top-bar"> 
    | {{ renderHTML(message) }} 
</div> 
<!-- not sure about second option, but either should work --> 

希望它幫助!