我是 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
关于javascript - 我不想转义 HTML 标签并在 Angular 应用程序中使用对象文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25760857/