Adit A. Pillai
Adit A. Pillai

Reputation: 667

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

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.

I have provided a link to the code above.

I am expecting the output to be a string "HelloWorld" which is underline.

ps:

Upvotes: 5

Views: 194

Answers (3)

devqon
devqon

Reputation: 13997

You need to use the angular-sanitize module:

<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:

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

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

Upvotes: 1

Pradeepb
Pradeepb

Reputation: 2562

You can use ng-bind-html and ng-bind-html-unsafe for that kind of purpose. you have to include ngSanitize from angular-sanitize.

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

The example is shown here

Upvotes: 3

nikjohn
nikjohn

Reputation: 21850

You want to just use a regular expression like so:

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

Working fiddle here

Upvotes: 1

Related Questions