2015-07-08 13 views
9

LA SITUAZIONE:AngularJs: come decodificare le entità HTML in HTML?

sto Bulding una pagina web il cui contenuto viene preso chiamando un'API che restituisce i dati in formato JSON.

Il problema è che i tag html sono dati come entità HTML, che deve essere decodificato.

ESEMPIO:

Questo è esempio di JSON mi occupo:

<p align="justify"><strong>15<sup>th</sup> HERE THERE IS A BOLD TEXT </strong> HERE SOME NORMAL TEXT... 

TENTATIVO:

ho ricerca spendere tempo e sembra più difficile di quanto pensato. Guardando in Google e simili SO domanda, una possibile soluzione è quella di utilizzare il ng-bing-html

chiamata API:

$http.get('http://API/page_content').then(function(resp) 
{ 
    $scope.content_test = resp.data[0].content; 
} 

Filtro:

.filter('trusted', ['$sce', function($sce){ 
    return function(text) { 
     return $sce.trustAsHtml(text); 
    }; 
}]) 

Ng-bind-html nel vista angolare:

<div ng-bind-html=" content_test | trusted"></div> 

OUTPUT:

Questa è l'uscita nella vista (esattamente come si vede):

<p align="justify"><strong>15<sup>th<\/sup> HERE THERE IS A BOLD TEXT<\/strong> HERE SOME NORMAL TEXT... 

ma quello che ho bisogno di vedere è il testo formattato correttamente:

Qui c'è un testo in grassetto Ecco alcuni Testo normale ...

LA DOMANDA:

Come posso decodificare HTML it in un formato HTML corretto in AngularJs?

risposta

13

penso che è necessario eseguire un altro "decodifica" step prima di passare a $sce.Ad esempio come questo:

app.filter('trusted', ['$sce', function($sce) { 
    var div = document.createElement('div'); 
    return function(text) { 
     div.innerHTML = text; 
     return $sce.trustAsHtml(div.textContent); 
    }; 
}]); 

Demo:http://plnkr.co/edit/LrT4tgYtTu4CPrOAidra?p=preview

6

Aggiungere il angular.sanitize.js

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular-sanitize.js"></script> 

aggiungere la dipendenza come,

var app = angular.module('plunker', ['ngSanitize']); 

SOCIETÀ decodificare la stringa HTML e passarlo al NG-bind-html.

$http.get('http://API/page_content').then(function(resp) 
{ 
    var html = resp.data[0].content; 

    var txt = document.createElement("textarea"); 
    txt.innerHTML = html; 


    $scope.content_test = txt.value; 

    //if you use jquery then use below 
    //$scope.content_test = $('<textarea />').html(html).text();   
} 

<div ng-bind-html="content_test"></div> 

Penso che si possa evitare il filter vedere l'esempio di seguito.

example

+0

Grazie mille! Funziona correttamente! Ho accettato l'altro solo perché può essere più riutilizzabile e prendere meno codice. Ma anche la tua risposta è corretta. Posso dare un vantaggio e specificarlo in una modifica alla mia domanda. – johnnyfittizio

+0

sì no prob :) cheerz –