AngularJS - Remove \n from data

后端 未结 6 1845
时光取名叫无心
时光取名叫无心 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:33

    You can also use a custom filter to replace \n to
    .

    And the filter.

    angular.module('myApp', [])
      .filter('nl2br', function(){
          return function(text) {
               return text ? text.replace(/\n/g, '
    ') : ''; }; });

    ** EDIT/UPDATE - 2014-12-10 **

    Since new versions of Angular removed ng-bind-html-unsafe @Tamlyn answer is now the best answer. I just changed the way $sce got injected into the function for speed purpose.

    HTML

    JS

    .filter('nl2br', ['$sce', function ($sce) {
        return function (text) {
            return text ? $sce.trustAsHtml(text.replace(/\n/g, '
    ')) : ''; }; }]);

    jsFiddle

提交回复
热议问题