AngularJS: newline characters to paragraph elements

时间秒杀一切 提交于 2019-12-18 13:26:08

问题


Within Angular, I need to generate a series of paragraph elements from a block of text containing newline characters?

I can think of a couple of ways to do this. However I am wondering whether there is an "official" Angular way or just what the most elegant approach would be within the AngularJS context.

An Example

From:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. \n
Sed diam nonummy nibh euismod tincidunt ut laoreet dolore. \n
Magna aliquam erat volutpat. Ut wisi enim ad minim veniam.

to:

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
<p>Sed diam nonummy nibh euismod tincidunt ut laoreet dolore.</p>
<p>Magna aliquam erat volutpat. Ut wisi enim ad minim veniam.</p>

I can think of a number of ways to do this:

  1. Modify the text in the controller (though I prefer to avoid modifying my models)
  2. Using a directive, and generating paragraphs in a link function (seems overly cumbersome).
  3. Using a filter (my current favourite) to create an array to pipe into ng-repeat

回答1:


The best solution I could think of was to create a filter:

angular.module('myApp').
filter('nlToArray', function() {
  return function(text) {
      return text.split('\n');
  };
});

This takes a block of text and creates a new array element for each paragraph.

This array can then be plugged into an ng-repeat directive:

<p ng-repeat="paragraph in textBlock|nlToArray track by $index">{{paragraph}}</p>



回答2:


var myApp = angular.module('myApp', ['ngSanitize']);
myApp.controller('myCtrl', function($scope){
    $scope.myText = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\nSed diam nonummy nibh euismod tincidunt ut laoreet dolore.\nMagna aliquam erat volutpat. Ut wisi enim ad minim veniam."
});
myApp.filter('nl2p', function () {
    return function(text){
        text = String(text).trim();
        return (text.length > 0 ? '<p>' + text.replace(/[\r\n]+/g, '</p><p>') + '</p>' : null);
    }
});

http://jsfiddle.net/moderndegree/934aZ/




回答3:


You might solve this with css property and use {{text}} into p html element

 white-space: pre-line;



回答4:


This is a silly hack, but it works around paragraphs being enclosed around other tags, such as <p><h3>:

text = '<p>' + text.replace(/[\r\n]+/g, '</p><p>') + '</p>';
// delete blank lines
text = text.replace(/<p>\s*?<\p>/g, '');
// delete erroneous paragraph enclosed tags
text = text.replace(/<p>\s*?(<.+?>)\s*?(.+?)\s*?(<\/.+?>)\s*?<\/p>/g, '$1$2$3');


来源:https://stackoverflow.com/questions/17238977/angularjs-newline-characters-to-paragraph-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!