我是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上。
答案 0 :(得分:2)
您可以定义secureHtml
过滤器。该过滤器会将您的表达式信任为HTML
youApp.filter('secureHtml', function ($sce) {
return function (input) {
return $sce.trustAsHtml(input);
}
})
然后,您可以在模板中使用过滤器,如下所示:
<div ng-bind-html="harmlessSnippet | secureHtml"></div>
使用您的示例工作plunkr:http://plnkr.co/edit/IsW7Q6s4bySp8Eim40kf?p=preview
答案 1 :(得分:2)
<!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