How to render a HTML tag from json value using angularJs

后端 未结 2 685
深忆病人
深忆病人 2020-12-30 09:43

// json is like this

\"_unparsedString\": \"

test<\\/p>\"

// HTML

Preamble : \'{{item2._unparse
相关标签:
2条回答
  • 2020-12-30 10:11

    Instead of passing string to view directly, you should use sce.trustAsHtml to pre-process the html.

    $scope.bindHTML = $sce.trustAsHtml(item2._unparsedString);
    

    Then in your view template, use ng-bind-html to handle html binding.

    <div>Preamble : <div ng-bind-html="bindHTML"></div></div>
    

    As you mentioned you have an array of object, it's not that easy to cast them in your controller, you can bind $sce to your $scope then call trustAsHtml in your view

    So in your controller

    myapp.controller('mainController', function ($scope, $http, $filter, $sce) {
       $scope.$sce = $sce;
    ...
    }
    

    Then in your html view

    <div>Preamble {{$index+1}} : <span ng-bind-html="$sce.trustAsHtml(item1.Preamble._unparsedString)"></span></div>
    
    0 讨论(0)
  • 2020-12-30 10:26

    Please check this working example: http://jsfiddle.net/Shital_D/b9qtj56p/6/

    Download file - angular-sanitize.js and include it in your app.

    var app = angular.module('myApp', ["ngSanitize"]);       
    
    app.controller('myController', function($scope,$compile) {
        $scope.html = '<p>Your html code</p>';
    });
    
    <div ng-app="myApp">
         <div ng-controller="myController">
         <p ng-bind-html="html"></p>
    </div>
    

    0 讨论(0)
提交回复
热议问题