【问题标题】:AngularJS is rendering <br> as text not as a newlineAngularJS 将 <br> 呈现为文本而不是换行符
【发布时间】:2013-02-04 11:39:32
【问题描述】:

我确定以前有人问过这个问题,但我找不到答案。

我有一个 AngularJS 脚本,它从数据库中提取然后呈现到内容。除了我试图用新行连接一些单词的几个地方之外,一切都正常工作。

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

如果我使用上述代码的第一行,我看不到任何内容,但重新生成的 html 中没有新行。如果我使用第二行,&lt;br&gt; 将呈现为文本,输出如下所示:

Instinct<br>Media

而不是

Instinct
Media

如果有帮助的话,我可以发布完整的脚本,但我猜有些简单的东西我没有看到。

更新 这是完整的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>

【问题讨论】:

  • 它可能将CATEGORY 输出为TextNode
  • 我猜这是真的,有没有办法在 TextNode 中换行?
  • 所以我假设我们至少需要查看您设置的绑定。
  • 我不相信有任何方法可以在 TextNode 中添加换行符。

标签: javascript angularjs


【解决方案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/

【讨论】:

  • 我实际上在使用 ng-repeat。如果有帮助,我已在原始帖子中添加了所有代码
  • 这会产生&lt;div ng-bind-html="Instinct&lt;br&gt;Media"&gt;&lt;/div&gt;,但没有渲染任何内容。我也试过 &lt;div class="ng-bind-html: {{q.CATEGORY}};"&gt;&lt;/div&gt; 没有任何运气
  • 角链接损坏
  • 根据Migrating ...页面:ngBindHtmlUnsafe has been removed and replaced by ngBindHtml
  • 如果现在(我的情况)偶然发现这一点并收到Attempting to use an unsafe value in a safe context. 错误,请查看此答案:stackoverflow.com/a/25679834/5345701
【解决方案2】:

您需要使用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 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>

【讨论】:

  • 谢谢@blesh 我将 Shimiddy 标记为答案,因为他在过去一个小时一直在帮助我,但我会给你一个投票。再次感谢
  • 没有汗水。有一段时间,他的答案存在争议,首先是使用了错误的指令,然后甚至没有正确使用......即ng-bind-html="{{blah}}"。看起来你在我发帖的时候解决了。
  • +1 我希望真正了解 Angular 的人会出现。哈哈。
  • 我只是在看。我了解更多回答我知道完整答案的问题。我可以告诉你有你需要的大部分信息,你会到达那里。看来你已经继续前进了,所以我添加了一个答案。
【解决方案3】:

我是这样用的

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>

就是这样,我得到了我的 &lt;br/&gt; 标记

【讨论】:

    【解决方案4】:

    您可以使用\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>

    【讨论】:

    • 除了\n,还需要CSS来强制换行,这一点并不明显。不错。
    • 谢谢! angularjs模态模板ui-bootstrap短信
    • 这很好。我使用white-space: pre-wrap; 来换行
    • 这是最好和最简单的答案。很多时候 {{messageText}} 需要简单的格式,这是迄今为止更简单的方法。它允许您自定义每条消息的这些消息,而不必担心自定义 css 格式或 html 注入。
    • 简单干净。完美地为我工作。谢谢!!
    【解决方案5】:

    为什么这么复杂?

    我通过这种方式简单地解决了我的问题:

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

    如果字符串包含我从 textarea 保存数据时包含的“\n”,它将自动生成&lt;br /&gt;

    【讨论】:

    • 因为您的解决方案破坏了格式,因此它是 pre
    【解决方案6】:

    你也可以使用:

    String.fromCharCode(10);

    使用 CSS

    white-space: pre-line;
    

    这里是工作示例: https://jsfiddle.net/Nxja/3xtcqdej/1/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-15
      • 2015-07-11
      • 2010-12-12
      相关资源
      最近更新 更多