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>