user1376704
user1376704

Reputation:

Reading JSON in AngularJS prints HTML tag as it is

This is the JSFiddle file I am trying to get it work.

I have made a simple filter to change the \n newline character from JSON to <br> to give line break in the HTML, but it doesn't work as expected.

The question is: In the output <br> tag is displayed as it is instead of being rendered by browser as as line-break.

So far I have tried to make new filter with the $sce variable like

angular.module('myApp.filters', [])
  .filter('linebreak', function() {
    return function(text) {
        return text.replace(/\n/g, '<br>');
    }
})
.filter('to_trusted', ['$sce', function($sce){
            return function(text) {
                return $sce.trustAsHtml(text);
            };
        }]);

and pipe the filter in the ng-bind like:

<div ng-bind="data.para | linebreak | to_trusted"></div>

but this doesn't dolve the problem. any hints how to tell Browser that
is HTML and render it as line break, in this scenario?

Upvotes: 2

Views: 4651

Answers (2)

Nitish Kumar
Nitish Kumar

Reputation: 4870

Use ng-bind-html for html binding.

Replace

ng-bind

To:

ng-bind-html

See Angular Docs For ngBindHtml

Upvotes: 0

NEOLPAR
NEOLPAR

Reputation: 382

When you use $sce in html you have to use the ng-bind-html directive instead of ng-bind:

<div ng-app="myApp">
    <div ng-controller="jsonCtrl">
        <div ng-repeat="data in textFile">
            <div ng-bind-html="data.para | linebreak | to_trusted">        </div>
      </div>
    </div>
</div>

You can see this working here

Upvotes: 4

Related Questions