AngularJS $sce 只信任某些元素
AngularJS $sce only trust certain elements
假设以下字符串:
<b><i><anotherelement>Hello World</anotherelement></i></b>
我只想让粗体元素起作用,而斜体元素(和任何其他元素!)保持不变,所以输出是:
<i><anotherelement>Hello World</anotherelement></i>
.
目前我使用:
function outputHtml($element, value){
$element.html($sanitize(value));
}
该解决方案信任 $sce 包附带的所有元素,因此它对我没有用:(
任何帮助将不胜感激,
谢谢!
检查这个 fiddle - http://jsfiddle.net/3J25M/764/
控制器-
angular.module('ngBindHtmlExample', ['ngSanitize'])
.controller('ngBindHtmlCtrl', ['$scope','$sce', function($scope, $sce) {
$scope.value = '<i><anotherelement>Hello World</anotherelement></i>';
$scope.myHTML = $sce.trustAsHtml('<b ng-bind="value"></b>');
}])
.directive('compileTemplate', function($compile, $parse){
return {
link: function(scope, element, attr){
var parsed = $parse(attr.ngBindHtml);
function getStringValue() {
return (parsed(scope) || '').toString();
}
// Recompile if the template changes
scope.$watch(getStringValue, function() {
$compile(element, null, -9999)(scope); // The -9999 makes it skip directives so that we do not recompile ourselves
});
}
}
});
HTML -
<div ng-app="ngBindHtmlExample">
<div ng-controller="ngBindHtmlCtrl">
<p ng-bind-html="myHTML" compile-template></p>
</div>
</div>
希望对您有所帮助!!
假设以下字符串:
<b><i><anotherelement>Hello World</anotherelement></i></b>
我只想让粗体元素起作用,而斜体元素(和任何其他元素!)保持不变,所以输出是:
<i><anotherelement>Hello World</anotherelement></i>
.
目前我使用:
function outputHtml($element, value){
$element.html($sanitize(value));
}
该解决方案信任 $sce 包附带的所有元素,因此它对我没有用:(
任何帮助将不胜感激, 谢谢!
检查这个 fiddle - http://jsfiddle.net/3J25M/764/
控制器-
angular.module('ngBindHtmlExample', ['ngSanitize'])
.controller('ngBindHtmlCtrl', ['$scope','$sce', function($scope, $sce) {
$scope.value = '<i><anotherelement>Hello World</anotherelement></i>';
$scope.myHTML = $sce.trustAsHtml('<b ng-bind="value"></b>');
}])
.directive('compileTemplate', function($compile, $parse){
return {
link: function(scope, element, attr){
var parsed = $parse(attr.ngBindHtml);
function getStringValue() {
return (parsed(scope) || '').toString();
}
// Recompile if the template changes
scope.$watch(getStringValue, function() {
$compile(element, null, -9999)(scope); // The -9999 makes it skip directives so that we do not recompile ourselves
});
}
}
});
HTML -
<div ng-app="ngBindHtmlExample">
<div ng-controller="ngBindHtmlCtrl">
<p ng-bind-html="myHTML" compile-template></p>
</div>
</div>
希望对您有所帮助!!