ng-bind-html 以防止在内容中执行脚本
ng-bind-html to prevent executing scripts in content
我面临的问题是我从具有 HTML 内容的服务器获取数据
<p> hello <a class='mention'data-id='1'>Amerr</a></p>
自 ng-bind-html Santaize 它将删除所有潜在威胁以及 data-id='1'。我需要我的指令。所以我用
- $compile 让我的指令作用于定位标签。
- $sce.trustAsHtml 到 return 编译代码。
所以如果有像
这样的文字
"<p> {{axy}} /p>\n"
$compile(html_code)($scope)
这将执行代码并导致 angular 执行导致问题的表达式。
帮我解决这个问题。
var controller= app.controller('Homecontrol', function($scope) {
$scope.body = socket.emit('hello');
$scope.to_trusted = function(html_code) {
if (/<[a-z][\s\S]*>/i.test(html_code)) {
var a = $compile(html_code)($scope);
return $sce.trustAsHtml(a[0].innerHTML);
} else {
return html_code;
}
}
});
app.directive('mention', function (){
return {
restrict: 'AEC',
transclude: true,
template: '<a ng-transclude ></a>',
replace: true,
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<p ng-bind-html=toTrust(body) ></p>
我终于通过解析字符串做到了。 Jquery.parseHTML 并编译了所需的 DOM 需要 $compile for 指令对其进行操作。并替换为 DOM.
我面临的问题是我从具有 HTML 内容的服务器获取数据
<p> hello <a class='mention'data-id='1'>Amerr</a></p>
自 ng-bind-html Santaize 它将删除所有潜在威胁以及 data-id='1'。我需要我的指令。所以我用
- $compile 让我的指令作用于定位标签。
- $sce.trustAsHtml 到 return 编译代码。
所以如果有像
这样的文字"<p> {{axy}} /p>\n"
$compile(html_code)($scope)
这将执行代码并导致 angular 执行导致问题的表达式。 帮我解决这个问题。
var controller= app.controller('Homecontrol', function($scope) {
$scope.body = socket.emit('hello');
$scope.to_trusted = function(html_code) {
if (/<[a-z][\s\S]*>/i.test(html_code)) {
var a = $compile(html_code)($scope);
return $sce.trustAsHtml(a[0].innerHTML);
} else {
return html_code;
}
}
});
app.directive('mention', function (){
return {
restrict: 'AEC',
transclude: true,
template: '<a ng-transclude ></a>',
replace: true,
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<p ng-bind-html=toTrust(body) ></p>
我终于通过解析字符串做到了。 Jquery.parseHTML 并编译了所需的 DOM 需要 $compile for 指令对其进行操作。并替换为 DOM.