为什么要要$sce
?因为angularJS里好些地方,比如路径默认是个字符串,不会认为是路径,从而访问不到我们需要的东西,那么我们就可以通过$sce
告诉angualrJS这个路径,这样是很安全滴。它有以下几种:
$sce.trustAs(type,name);
$sce.trustAsUrl(value);
$sce.trustAsHtml(value);
$sce.trustAsResourceUrl(value);
$sce.trustAsJs(value);
1.trustAsResourceUrl
<html>
<head>
<meta charset="utf-8">
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
第一种方式:<br/>
有$sce处理:<audio ng-src="{{sceControl(formData.mediaUrl)}}" controls="controls">您的浏览器不支持html5</audio><br/>
无$sce处理:<audio ng-src="{{formData.mediaUrl}}" controls="controls">您的浏览器不支持html5</audio><br/><br/>
第二种方式:<br/>
<audio ng-src="{{data.url}}" controls="controls">您的浏览器不支持html5</audio>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$sce){
//第一种方式数据源
$scope.formData={
"name":"视频",
"mediaUrl":"http://res.audiogroup.cn/res/upload/agx_ims_creative/audio/20160307/bpryk96.mp3"//视频路径
};
$scope.sceControl = $sce.trustAsResourceUrl;//第一种处理方式
//第二种方式数据源
$scope.data={
"name":"视频",
"url":"http://res.audiogroup.cn/res/upload/agx_ims_creative/audio/20160307/bpryk96.mp3"//视频路径
};
$scope.data.url = $sce.trustAsResourceUrl($scope.data.url);//第二种处理方式
});
</script>
</body>
</html>
2.trustAsHtml
<body>
<div ng-app="myApp" ng-controller="myCtrl">
未处理的:
<div ng-repeat="item in formData">
{{item.name}} :{{item.htmlVal}}
</div>
<br/>处理过的:<button ng-click="look()">查看处理结果</button>
<div ng-repeat="item in data">
{{item.name}} :<p ng-bind-html = "item.htmlVal"></p>
</div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$sce){
//未处理数据源
$scope.formData=[
{"name":"张春玲","htmlVal":"我是<span style='color:red;'>张春玲<span>"},
{"name":"sb","htmlVal":"我是<span style='color:red;'>sb<span>"}
];
//处理结果
$scope.look = function(){alert
$scope.data=[
{"name":"张春玲","htmlVal":"我是<span style='color:red;'>张春玲<span>"},
{"name":"sb","htmlVal":"我是<span style='color:red;'>sb<span>"}
];
for(var i=0;i<$scope.data.length;i++){
$scope.data[i].htmlVal = $sce.trustAsHtml($scope.data[i].htmlVal);
}
};
});
</script>
</body>