2013-02-19 6 views
42

Sono sicuro che questo è stato chiesto prima ma non riesco a trovare la risposta.AngularJS sta riproducendo <br> come testo non come newline

Ho uno script AngularJS che sta eseguendo il pull da un DB e quindi il rendering sul contenuto. Tutto funziona correttamente, tranne un paio di punti in cui sto cercando di concatenare alcune parole con nuove linee tra di loro.

**in the script.js** 
groupedList[aIndex].CATEGORY = existingCategory+'\n'+thisCategory; 
groupedList[aIndex].CATEGORY = existingCategory+'<br>'+thisCategory; 

Se uso la prima riga del codice di cui sopra non vedo nulla, ma non c'è una nuova linea nel codice HTML redered. Se uso la seconda linea del <br> visualizzate come testo e l'output simile a questo:

Instinct<br>Media 

invece di

Instinct 
Media 

posso postare lo script completo se sarebbe utile, ma sto indovinando c'è qualcosa di semplice che non vedo.

UPDATE Ecco l'js pieni

function qCtrl($scope, $filter, $http, $timeout){ 

    $scope.getCategories = function(){$http.post('quote.cfc?method=getCategories').success(function(data) { $scope.categories = data; }); } 
    $scope.getClassifications = function(){$http.post('quote.cfc?method=getClassifications').success(function(data) { $scope.classifications = data; }); } 
    $scope.getIndustries = function(){$http.post('quote.cfc?method=getIndustries').success(function(data) { $scope.industries = data; }); } 
    $scope.getKeywords = function(){$http.post('quote.cfc?method=getKeywords').success(function(data) { $scope.keywords = data; }); } 
    $scope.getSources = function(){$http.post('quote.cfc?method=getSources').success(function(data) { $scope.sources = data; }); } 

    $scope.getAllQuotes = function(){$http.post('quote.cfc?method=getAllQuotesJoined').success(function(data) { $scope.allQuotes = data; }); } 

    $scope.initScopes = function(){ 
     $scope.getCategories(); 
     $scope.getClassifications(); 
     $scope.getIndustries(); 
     $scope.getKeywords(); 
     $scope.getSources(); 
     $scope.getAllQuotes(); 
    } 
    $scope.initScopes(); 

    // SEARCH QUOTES 
    $scope.filteredQuotes = $scope.allQuotes; 
    $scope.search = {searchField:''}; 

    $scope.searchQuote = function(){ 
     var filter = $filter('filter'); 
     var searchCrit = $scope.search; 
     var newlist = $scope.allQuotes; 
     var groupedList = []; 
     var idList = []; 
     newlist = filter(newlist,{TESTQUOTE:searchCrit.searchField}); 
     for(i=0;i<10;i++){ 
      aIndex = idList.contains(newlist[i].TESTIMONIALID); 
      if(aIndex >= 0){ 
       thisKeyword = newlist[i].KEYWORD; 
       thisClassification = newlist[i].CLASSIFICATION; 
       thisCategory = newlist[i].CATEGORY; 
       existingKeyword = groupedList[aIndex].KEYWORD; 
       existingClassification = groupedList[aIndex].CLASSIFICATION; 
       existingCategory = groupedList[aIndex].CATEGORY; 
       if(thisKeyword != '' && existingKeyword.indexOf(thisKeyword) == -1){ 
        groupedList[aIndex].KEYWORD = existingKeyword+' - '+thisKeyword; 
       } 
       if(thisClassification != '' && existingClassification.indexOf(thisClassification) == -1){ 
        groupedList[aIndex].CLASSIFICATION = existingClassification+' \n '+thisClassification; 
       } 
       if(thisCategory != '' && existingCategory.indexOf(thisCategory) == -1){ 
        groupedList[aIndex].CATEGORY = existingCategory+'<br>'+thisCategory; 
       }    
      } else { 
       idList.push(newlist[i].TESTIMONIALID); 
       groupedList.push(newlist[i]); 
      } 
     } 
     $scope.filteredQuotes = groupedList; 
     } 
} 
Array.prototype.contains = function (needle) { 
    for (j in this) { 
     if (this[j] == needle) return j; 
    } 
    return -1; 
} 

Ecco il codice HTML

<div ng-repeat="q in filteredQuotes" class="well clearfix"> 
         <h3>{{q.TITLE}}</h3> 
         <div class="row-fluid" style="margin-bottom:5px;"> 
          <div class="span3 well-small whBG"><h4>Classification</h4>{{q.CLASSIFICATION}}</div> 
          <div class="span3 well-small whBG pipeHolder"><h4>Categories</h4>{{q.CATEGORY}}</div> 
          <div class="span3 well-small whBG"><h4>Key Words</h4>{{q.KEYWORD}}</div> 
          <div class="span3 well-small whBG"><h4>Additional</h4>Industry = {{q.INDUSTRY}}<br>Source = {{q.SOURCE}}</div> 
         </div> 
         <div class="well whBG">{{q.TESTQUOTE}}</div> 
         <div class="tiny"> 
          Source comment : {{q.SOURCECOMMENT}}<br> 
          Additional Comment : {{q.COMMENT}} 
         </div> 
        </div> 
       </div> 
+1

Probabilmente è in uscita 'CATEGORY' come TextNode – Shmiddty

+0

Suppongo che sia vero, c'è un modo per ottenere una nuova riga in un TextNode? – Lance

+0

Quindi presumo che avremo almeno bisogno di vedere l'associazione che hai impostato. – Shmiddty

risposta

38

potrei sbagliarmi, perché non ho mai usato angolare, ma credo che probabilmente si sta utilizzando ng-bind, che creerà solo un TextNode.

Si consiglia di utilizzare ng-bind-html invece.

http://docs.angularjs.org/api/ngSanitize.directive:ngBindHtml

Aggiornamento: Sembra che avrete bisogno di utilizzare ng-bind-html-unsafe='q.category'

http://docs.angularjs.org/api/ng.directive:ngBindHtmlUnsafe

Ecco una demo:

http://jsfiddle.net/VFVMv/

+0

Attualmente sto usando ng-repeat. Ho aggiunto tutto il codice nel mio post originale se questo aiuta – Lance

+0

Questo produce '

' ma non viene eseguito il rendering. Ho anche provato '
' senza fortuna – Lance

+0

Grazie a @Shmiddty per tutto l'aiuto. Funziona alla grande – Lance

24

è necessario o l'uso ng-bind-html-unsafe ... o avete bisogno di includere il modulo ngSanitize e utilizzare ng-bind-html:

con ng-bind-html-non sicuro

Utilizzare questo se si considera attendibile l'origine del HTML si sta rendendo lo farà rendere l'output grezzo di qualunque cosa tu ci metta.

<div><h4>Categories</h4><span ng-bind-html-unsafe="q.CATEGORY"></span></div> 

O con ng-bind-html

Utilizzare questo se non vi fidate la fonte del HTML (vale a dire che è l'input dell'utente). Sanitizza l'html per assicurarsi che non includa cose come tag script o altre fonti di potenziali rischi per la sicurezza.

Assicurati di includere questo:

<script src="http://code.angularjs.org/1.0.4/angular-sanitize.min.js"></script> 

quindi fare riferimento nel modulo di applicazione:

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

quindi utilizzarlo:

<div><h4>Categories</h4><span ng-bind-html="q.CATEGORY"></span></div> 
+0

Grazie @blesh ho contrassegnato Shimiddy come la risposta dato che mi ha aiutato per l'ultima ora ma ti darò una votazione. Grazie ancora – Lance

+0

Nessun problema. Per un po 'ci fu una lotta sulla sua risposta, prima dove veniva usata la direttiva sbagliata, e poi quando non era nemmeno usata correttamente ... cioè 'ng-bind-html =" {{blah}} "' . Sembra che tu l'abbia elaborato mentre stavo pubblicando. –

+3

+1 Speravo che qualcuno che in realtà sapeva che Angular si sarebbe presentato. Haha. – Shmiddty

2

Ho usato come questo

function chatSearchCtrl($scope, $http,$sce) { 
// some more my code 

// take this 
data['message'] = $sce.trustAsHtml(data['message']); 

$scope.searchresults = data; 

e in html che ho fatto

<p class="clsPyType clsChatBoxPadding" ng-bind-html="searchresults.message"></p> 

questo è tutto ho la mia tag <br/> reso

46

È possibile utilizzare \n per concatenare le parole e quindi applicare questo stile al div contenitore.

style="white-space: pre;" 

Maggiori informazioni si possono trovare presso https://developer.mozilla.org/en-US/docs/Web/CSS/white-space

<p style="white-space: pre;"> 
 
    This is normal text. 
 
</p> 
 
<p style="white-space: pre;"> 
 
    This 
 
    text 
 
    contains 
 
    new lines. 
 
</p>

+8

Amo questa risposta!Dovrebbe essere la risposta accettata! –

+0

Non è immediatamente ovvio che, oltre a '\ n', anche il CSS sia necessario per applicare le nuove linee. Ben fatto. – dmvianna

+0

Questo ha funzionato per me e sto usando Angular 2. – Rodrigo

2

Perché così complicato?

ho risolto il problema in questo modo semplicemente:

<pre>{{existingCategory+thisCategory}}</pre> 

Farà <br /> automaticamente se la stringa contiene '\ n' che contengono, quando stavo salvando i dati da textarea.

+0

Il coz della soluzione si interrompe formando quindi '' 'pre''' – ruX

+0

approciando (y) –

Problemi correlati