angularjs ng-bind-html 指令 对html标签转译

文章参考

http://www.tuicool.com/articles/2eIrIz

http://www.runoob.com/angularjs/ng-ng-bind-html.html

 

在工作中遇到问题:用户在后台添加一篇新闻,在数据库中存储的是HTML代码,从数据库查询出来之后结果把HTML代码显示出来。

 

 

解决办法:使用ng-bind-html 指令,能够对html代码的标签转译,在浏览器中显示

 

ng-bind-html 指令会自动过滤掉标签内的样式?

所谓sce即“Strict Contextual Escaping”的缩写。翻译成中文就是“严格的上下文模式”也可以理解为安全绑定吧。

$sce干的事情来看就是将语境中存在的跨站攻击的风险给干掉.

我们返回的内容中包含一系列的html标记,它可以通过使用$sce.trustAsHtml()。该方法将值转换为特权所接受并能安全地使用“ng-bind-html”。所以,我们必须在我们的控制器中引入$sce服务.

代码如下

/**
 * 公司简介service
 * */
angular.module("hkApp").factory("companyIntroduceIndexCompanyService",["$http","$sce",function($http,$sce){
    return {
    	//获取公司简介
		getCompanyIntroduce:function(__scope__){
			var url = "/index.php/Admin/Page/companyPage.html";
			var formData = {
				id:2
			};
			 $http.post(url,formData)
             .success(function(response, status, headers, config){
             	if(response.status == 1){
             		
             		//__scope__.content = response.data.content;
             		__scope__.content = $sce.trustAsHtml(response.data.content);
             	}
         	});
		}
    }
}]);

【1】angular源码分析:angular中入境检察官$sce

【2】野兽的 Angular 学习 - - scesce和sceDelegate

【3】$sce官方手册

猜你喜欢

转载自hbiao68.iteye.com/blog/2297519