AngularJS отображает как текст не как новую строку
Я уверен, что это было задано раньше, но я не могу найти ответ.
У меня есть AngularJS script, который вытаскивает из БД, а затем выводит на контент. Все работает правильно, за исключением нескольких мест, которые я пытаюсь объединить несколько слов с новыми строками между ними.
**in the script.js**
groupedList[aIndex].CATEGORY = existingCategory+'\n'+thisCategory;
groupedList[aIndex].CATEGORY = existingCategory+'<br>'+thisCategory;
Если я использую первую строку вышеприведенного кода, я ничего не вижу, но в redered html нет новой строки. Если я использую вторую строку, <br>
получают в виде текста, и результат выглядит следующим образом:
Instinct<br>Media
вместо
Instinct
Media
Я могу опубликовать полный script, если бы это было полезно, но я предполагаю, что есть что-то простое, чего я просто не вижу.
UPDATE
Вот полный js
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;
}
Вот 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
Я мог ошибаться, потому что я никогда не использовал Angular, но я полагаю, что вы, вероятно, используете ng-bind
, который будет создавать только TextNode.
Вместо этого вы хотите использовать ng-bind-html
.
http://docs.angularjs.org/api/ngSanitize.directive:ngBindHtml
Обновить. Похоже, вам нужно использовать ng-bind-html-unsafe='q.category'
http://docs.angularjs.org/api/ng.directive:ngBindHtmlUnsafe
Вот демо:
http://jsfiddle.net/VFVMv/
Ответ 2
Вы можете использовать \n
для конкатенации слов, а затем применить этот стиль к контейнеру div.
style="white-space: pre;"
Более подробную информацию можно найти на 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>
Ответ 3
Вам нужно либо использовать ng-bind-html-unsafe
... или вам нужно включить модуль ngSanitize и использовать ng-bind-html
:
с ng-bind-html-unsafe
Используйте это, если вы доверяете источнику HTML-рендеринга, который будет отображать исходный вывод того, что вы вложили в него.
<div><h4>Categories</h4><span ng-bind-html-unsafe="q.CATEGORY"></span></div>
ИЛИ с ng-bind-html
Используйте это, если вы НЕ доверяете источнику HTML (т.е. вводите его пользователем). Он будет дезинфицировать html, чтобы убедиться, что он не включает такие вещи, как теги script или другие источники потенциальных угроз безопасности.
Убедитесь, что вы включили это:
<script src="http://code.angularjs.org/1.0.4/angular-sanitize.min.js"></script>
Затем укажите его в своем прикладном модуле:
var app = angular.module('myApp', ['ngSanitize']);
ТОГДА используйте его:
<div><h4>Categories</h4><span ng-bind-html="q.CATEGORY"></span></div>
Ответ 4
Я так использовал
function chatSearchCtrl($scope, $http,$sce) {
// some more my code
// take this
data['message'] = $sce.trustAsHtml(data['message']);
$scope.searchresults = data;
и в html я сделал
<p class="clsPyType clsChatBoxPadding" ng-bind-html="searchresults.message"></p>
thats it я получаю тэг <br/>
Ответ 5
Почему так сложно?
Я решил эту проблему просто так:
<pre>{{existingCategory+thisCategory}}</pre>
Он автоматически сделает <br />
, если строка содержит '\n', которые содержат, когда я сохранял данные из textarea.