简体   繁体   English

如何解析嵌入在JavaScript对象内部的字符串中的html?

[英]How to parse the html which is embedded in a string inside a JavaScript object?

JsFiddle JsFiddle

<script>
  angular.module('module', []);

  angular.module('module').controller('hello', function($scope) {
    $scope.obj = {
      "text": "<u>HelloWorld</u>"
    };

  });

</script>

<body>

  <div ng-app='module' ng-controller='hello'>
    Current:{{obj.text}}

    <br>
    <br> Expected:<u>HelloWorld</u>
  </div>
</body>

I am trying to read an object stored in a JSON and then print it on my web page. 我试图读取存储在JSON中的对象,然后将其打印在我的网页上。

I have provided a link to the code above. 我提供了到上面代码的链接。

I am expecting the output to be a string "HelloWorld" which is underline. 我期望输出是下划线的字符串“ HelloWorld”。

ps: ps:

  • I cannot edit the JSON 我无法编辑JSON
  • obj is the object that is being fetched, I could not share the JSON so i have used a hardcoded value. obj是正在获取的对象,我无法共享JSON,所以我使用了硬编码值。

You can use ng-bind-html and ng-bind-html-unsafe for that kind of purpose. 您可以出于这种目的使用ng-bind-htmlng-bind-html-unsafe you have to include ngSanitize from angular-sanitize . 您必须从angular-sanitize包括ngSanitize

<p ng-bind-html="obj.text"></p>

The example is shown here 此处显示示例

You want to just use a regular expression like so: 您只想使用如下正则表达式:

$scope.obj.text =  $scope.obj.text.replace(/(<([^>]+)>)/ig,"");

Working fiddle here 在这里工作

You need to use the angular-sanitize module : 您需要使用angular-sanitize模块

<script src="path/to/installed/angular-sanitize/angular-sanitize.js"></script>

<script>
    angular.module("module", ["ngSanitize"]);

    angular.module('module').controller('hello', function($scope) {
        $scope.obj = {
            "text": "<u>HelloWorld</u>"
        };

    });

</script>

And your html: 和你的HTML:

<div ng-app='module' ng-controller='hello'>
    Current: <p ng-bind-html="obj.text"></p>

    <br>
    <br> Expected:<u>HelloWorld</u>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM