How can I preserve new lines in an AngularJS partial?

前端 未结 4 1691
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 16:53

Within an AngularJS partial I am looping over a list of entries as follows:

相关标签:
4条回答
  • 2020-12-02 17:08

    I make filters

    // filters js
    myApp.filter("nl2br", function($filter) {
     return function(data) {
       if (!data) return data;
       return data.replace(/\n\r?/g, '<br />');
     };
    });
    

    then

    // view
    <div ng-bind-html="article.description | nl2br"></div>
    
    0 讨论(0)
  • 2020-12-02 17:21
    // AngularJS filter
    angular.module('app').filter('newline', function($sce) {
        return function(text) {
            text = text.replace(/\n/g, '<br />');
            return $sce.trustAsHtml(text);
        }
    });
    
    // HTML
    <span ng-bind-html="someText | newline"></span>
    
    0 讨论(0)
  • 2020-12-02 17:23

    It is just basic HTML. AngularJS won't change anything about that. You could use a pre tag instead:

    <pre>{{ entry.content }}</pre>
    

    Or use CSS:

    p .content {white-space: pre}
    
    ...
    
    <p class='content'>{{ entry.content }}</p>
    

    If entry.content contains HTML code, you could use ng-bind-html:

    <p ng-bind-html="entry.content"></p>
    

    Don't forget to include ngSanitize:

    var myModule = angular.module('myModule', ['ngSanitize']);
    
    0 讨论(0)
  • 2020-12-02 17:26

    I fix it by adding pre-line:

    <style>
        pre{
            white-space: pre-line;
        }
    </style>
    My data:
     <pre>{{feedback.Content}}<pre>
    
    0 讨论(0)
提交回复
热议问题