javascript - 如何安全地将 HTML 从模型绑定(bind)到 View

标签 javascript angularjs ngsanitize

如果所有文本和样式都保存在 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>

欲了解更多信息,AngularJS ng-bind-html Directive API Reference .

关于javascript - 如何安全地将 HTML 从模型绑定(bind)到 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50181938/

相关文章:

javascript - 覆盖 JavaScript 会在 IE 中导致无限循环,但在 Firefox 中不会

javascript - 在 AngularJs 中绑定(bind)标签名称

javascript - 如何使 MarkerClusters 使用 Pane

javascript - 格式化transformRequest - Angular 到 PHP

javascript - 调试 AngularJS Internet Explorer 锁定

javascript - 使用 John Papa 的 AngularJS 风格指南,声明数据对象的正确方法是什么?

javascript - AngularJS:ngBindHtml 还包含子绑定(bind)?

javascript - AngularJS $sce 只信任某些元素

javascript - 防止多次点击事件并更改目标值