AngularJS - Remove \n from data

后端 未结 6 1843
时光取名叫无心
时光取名叫无心 2021-02-07 20:07

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:21

    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

提交回复
热议问题