AngularJS - Remove \n from data

后端 未结 6 1412
醉梦人生
醉梦人生 2021-02-07 19:52

What is the best way to catch and format the \"\\n\\n\" inside of text being passed from the server to display line breaks? Fiddle is here: http://jsfiddle.net/nicktest2222/2vYB

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-07 20:32

    You can create a simple filter that will split your string into paragraphs:

    .filter('lines', function() {
        return function(text) {
          return angular.isString(text) ? text.split(/\n/g) : text;
        }
      })   
    

    And use it in view to display them:

    {{ paragraph }}

    There is no need for bind-html-unsafe.

    See this in action in the snippet:

    angular.module('module', [])
      .filter('lines', function() {
        return function(text) {
          return angular.isString(text) ? text.split(/\n/g) : text;
        }
      })
      .controller('MyCtrl', function($scope) {
        $scope.myText = "First line\nSecondLine\nThird line\n\n\n\n\nAlone line";
      });
    p {
      min-height: 1px;
    }
    
    

    {{ paragraph }}

    This is not my idea but I can't find the source right now

提交回复
热议问题