Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
87
rated 0 times [  92] [ 5]  / answers: 1 / hits: 16655  / 11 Years ago, fri, june 21, 2013, 12:00:00

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


More From » angularjs

 Answers
0

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>

[#77491] Thursday, June 20, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kileyr

Total Points: 112
Total Questions: 105
Total Answers: 114

Location: United States Minor Outlying Island
Member since Sat, May 28, 2022
2 Years ago
;