如果所有文本和样式都保存在 api 上,则将 html 代码显示为 html 代码
假设我正在使用文本编辑器,我不仅在 api 上保存了文本,还保存了 html 样式(例如 <align>
、<h1>
、blabla)。我想要的是在我的 html View 上显示文本,但使用样式。例如,如果我保存了 <h1><u>Hello there!</u><h1>
,我需要在我的 html View 中显示标题为 h1 并带有下划线的文本。
我获取 api 响应的代码:
function info(){
$http.get('/theApi')
.then(function(data){
$scope.product = data.data.Response;
});
}
返回这样的东西:
[{Name: "Chuck", Message: "<h1><u>Hello there!</u><h1>"}]
如果我这样传递数据:
{{product.Message}}
在我的 html View 中,我会得到:
<h1><u>Hello there!</u><h1>
那么,我该怎么做才能将文本作为标题 h1 并在 html View 中加下划线?
我正在使用 AnguarJs 和 Javascript。
提前致谢。
最佳答案
将ng-bind-html
指令与ngSanitize module 一起使用:
angular.module('bindHtmlExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', function($scope) {
$scope.myHTML =
'<h1><u>Hello there!</u><h1>';
}]);
<script src="//unpkg.com/angular/angular.js"></script>
<script src="//unpkg.com/angular-sanitize/angular-sanitize.js"></script>
<body ng-app="bindHtmlExample" ng-controller="ExampleController">
<input ng-model="myHTML">
<p ng-bind-html="myHTML"></p>
</body>
关于javascript - 如何安全地将 HTML 从模型绑定(bind)到 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50181938/