Javascript 允许在angular的方形支架内呈现html
假设我有一些html和javascript:Javascript 允许在angular的方形支架内呈现html,javascript,html,angularjs,Javascript,Html,Angularjs,假设我有一些html和javascript: $scope.test = "hello<br/>world"; <div>{{ test }}</div> angular显然会将其渲染为: <div>hello<br/>world</div> 这正是它应该如何工作的,但是,如果我想让它以html标记而不是文本的形式呈现呢 我知道这会导致安全问题,但出于好奇,我想知道 提前感谢。您可以使用AngularJS中的指令 <
$scope.test = "hello<br/>world";
<div>{{ test }}</div>
angular显然会将其渲染为:
<div>hello<br/>world</div>
这正是它应该如何工作的,但是,如果我想让它以html标记而不是文本的形式呈现呢
我知道这会导致安全问题,但出于好奇,我想知道
提前感谢。您可以使用AngularJS中的指令
<div ng-controller="ngBindHtmlCtrl">
<p ng-bind-html="trustedHtml"></p>
</div>
将相应地提供
出于安全考虑,在将HTML内容传递给范围变量myHTML之前,请使用以下方法对其进行清理:
$scope.trustedHtml = $sce.trustAsHtml($scope.html);
然后在上面列出的ng bind html指令中使用$scope.trustedHtml。您可以在AngularJS中使用该指令
<div ng-controller="ngBindHtmlCtrl">
<p ng-bind-html="trustedHtml"></p>
</div>
将相应地提供
出于安全考虑,在将HTML内容传递给范围变量myHTML之前,请使用以下方法对其进行清理:
$scope.trustedHtml = $sce.trustAsHtml($scope.html);
然后在上面列出的ng bind html指令中使用$scope.trustedHtml。您可以根据建议创建筛选器: HTML:
<div ng-controller="MyCtrl">
<div ng-bind-html="my_html | to_trusted"></div>
</div>
以下是javascript的显示方式:
var myApp = angular.module('myApp',[]);
angular.module('myApp')
.filter('to_trusted', ['$sce', function($sce){
return function(text) {
return $sce.trustAsHtml(text);
};
}]);
function MyCtrl($scope) {
$scope.my_html = '<div>hello<br/>world</div>';
}
您可以根据建议创建过滤器: HTML:
<div ng-controller="MyCtrl">
<div ng-bind-html="my_html | to_trusted"></div>
</div>
以下是javascript的显示方式:
var myApp = angular.module('myApp',[]);
angular.module('myApp')
.filter('to_trusted', ['$sce', function($sce){
return function(text) {
return $sce.trustAsHtml(text);
};
}]);
function MyCtrl($scope) {
$scope.my_html = '<div>hello<br/>world</div>';
}
我得到一个错误:错误:$sce:unsafe需要一个安全/可信的值我得到一个错误:错误:$sce:unsafe需要一个安全/可信的值