AngularJS - Remove \n from data

后端 未结 6 1400
醉梦人生
醉梦人生 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:40

    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

提交回复
热议问题