angular中的ng-bind-html指令和$sce服務

angular js的強大之處之一就是他的數據雙向綁定這一牛B功能,咱們會經常用到的兩個東西就是ng-bind和針對form的ng-model。但在咱們的項目當中會遇到這樣的狀況,後臺返回的數據中帶有各類各樣的html標籤。如:html

$scope.currentWork.description = 「hello,<br><b>今天咱們去哪裏?</b>」

咱們用ng-bind-html這樣的指令來綁定,結果卻不是咱們想要的。是這樣的api

hello,
今天咱們去哪裏?
怎麼辦呢?安全

對於angular 1.2一下的版本咱們必需要使用$sce這個服務來解決咱們的問題。所謂sce即「Strict Contextual Escaping」的縮寫。翻譯成中文就是「嚴格的上下文模式」也能夠理解爲安全綁定吧。來看看怎麼用吧。app

controller code:spa

$http.get('/api/work/get?workId=' + $routeParams.workId).success(function (work) {$scope.currentWork = work;});

HTML code:翻譯

<p> {{currentWork.description}}</p>

咱們返回的內容中包含一系列的html標記。表現出來的結果就如咱們文章開頭所說的那樣。這時候咱們必須告訴它安全綁定。它能夠經過使用$ sce.trustAsHtml()。該方法將值轉換爲特權所接受並能安全地使用「ng-bind-html」。因此,咱們必須在咱們的控制器中引入$sce服務雙向綁定

controller('transferWorkStep2', ['$scope','$http','$routeParams','$sce', function ($scope,$http, $routeParams, $sce) {
$http.get('/api/work/get?workId=' + $routeParams.workId)
.success(function (work) {
    $scope.currentWork = work;
    $scope.currentWork.description = $sce.trustAsHtml($rootScope.currentWork.description);
});

html code:code

<p ng-bind-html="currentWork.description"></p>

這樣結果就完美的呈如今頁面上了:orm

hellohtm

今天咱們去哪裏?

我們還能夠這樣用,把它封裝成一個過濾器就能夠在模板上隨時調用了

app.filter('to_trusted', ['$sce', function ($sce) {
return function (text) {
    return $sce.trustAsHtml(text);
};

}]);

html code:

<p ng-bind-html="currentWork.description | to_trusted"></p>

原文地址:http://www.w3cscript.com/Angular/2014-05-26/349.html

相關文章
相關標籤/搜索