我不想转义HTML标记,也不想在Angular应用程序中使用对象文字
I want not to escape HTML tags and to use object literal in Angular app
我是AngularJS的新手。我不想转义HTML标记,并编写了下面的代码。
起初,在定义deliberatelyTrustDangerousSnipet()
时,我成功地逃脱了HTML标记(在这个网站上有很好的顾问)。
其次,我想使用<div ng-bind-html="phone.snippet"></div>
。
<script>
angular.module('plunker', ['ngSanitize'])
.controller('MainCtrl', ['$scope', '$sce', function($scope, $sce) {
$scope.phone =
{'name': 'Nexus S',
'snippet': '<iframe width="560" height="315" src="//www.youtube.com/embed/-RRqZ7FAlG0?rel=0" frameborder="0" allowfullscreen></iframe>'};
// This works well
$scope.deliberatelyTrustDangerousSnippet = function() {
return $sce.trustAsHtml('<iframe width="560" height="315" src="//www.youtube.com/embed/-RRqZ7FAlG0?rel=0" frameborder="0" allowfullscreen></iframe>');
};
// This doesn't work
//$sce.trustAsHtml($scope.article.content);
}])
</script>
<div ng-controller="MainCtrl">
<div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div>
<!-- ### Can we write like below? ### -->
<div ng-bind-html="phone.snippet"></div>
</div>
代码也在Plunker上。
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.0/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.0/angular-sanitize.js"></script>
</head>
<body>
<script>
angular.module('plunker', ['ngSanitize'])
.controller('MainCtrl', ['$scope', '$sce', function($scope, $sce) {
$scope.phone =
{'name': 'Nexus S',
'snippet': '<iframe width="560" height="315" src="//www.youtube.com/embed/-RRqZ7FAlG0?rel=0" frameborder="0" allowfullscreen></iframe>'};
$scope.phone.snippet = $sce.trustAsHtml($scope.phone.snippet);
}])
</script>
<div ng-controller="MainCtrl">
<div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div>
<!-- ### Can we write like below? ### -->
<div ng-bind-html="phone.snippet"></div>
</div>
</body>
</html>
另一个选项是添加ngSanitize.js
,这样就不需要执行$sce.trustAsHtml
您可以定义一个secureHtml
过滤器。该过滤器会将您的表达式信任为类似的HTML
youApp.filter('secureHtml', function ($sce) {
return function (input) {
return $sce.trustAsHtml(input);
}
})
然后你可以在你的模板中使用过滤器,如下所示:
<div ng-bind-html="harmlessSnippet | secureHtml"></div>
与你的例子一起工作:http://plnkr.co/edit/IsW7Q6s4bySp8Eim40kf?p=preview
相关文章:
- Canvas Html5绘图应用程序,移动画布会导致重大问题
- Emberjs应用程序加载在除Index之外的所有路由上
- 使用电话间隙在Android应用程序中显示SQL Lite的数据
- 在AngularJS应用程序中使用封装指令和路由的推荐方式是什么
- Windows8应用程序(html&Javascript):从图片库(除了文件选择器)显示图像的另一种方式
- angular 1.5应用程序中的导航栏
- 在Web应用程序中使用Highcharts javascript
- angularjs+rails应用程序中未显示模板
- 使用acess代币登录Facebook,并通过网络应用程序离线发布
- 从HTTPGET返回一个自定义对象列表,以便在Angular 2应用程序中使用
- 科尔多瓦页面类应用程序中的多个谷歌地图
- 使用谷歌应用程序脚本将服务器端数据表返回到客户端
- Angularjs-utils高亮过滤器在搜索时破坏应用程序
- 在phonegap应用程序内部重定向不起作用
- 使用谷歌应用程序脚本从工作表中获取值并将其显示在文本框中
- MockJax没有在JavaScript应用程序中发送对我AJAX请求的响应
- Node.js正在更改应用程序以使用集群模块
- 在openshift node js应用程序中获取请求
- 如何在Facebook上的iframe应用程序中使后退按钮返回到上一页
- 我不想转义HTML标记,也不想在Angular应用程序中使用对象文字