AngularJS:换行符为段落元素 [英] AngularJS: newline characters to paragraph elements
问题描述
在角,我需要从包含换行字符的文本块生成一系列段落元素的?
我能想到的几个方法可以做到这一点。但是我想知道是否有一个官方角方式,或只是最优雅的方式将是AngularJS范围内的东西。
为例
从:
Lorem存有悲坐阿梅德,consectetuer adipiscing ELIT。 \\ n结果
桑达直径nonummy NIBH euismod tincidunt UT laoreet dolore。 \\ n结果
麦格纳aliquam ERAT volutpat。 UT WISI enim广告微量veniam。
块引用>到
< P> Lorem存有悲坐阿梅德,consectetuer adipiscing ELIT< / P>
&所述p为H.;桑达直径nonummy NIBH euismod tincidunt UT laoreet dolore&下; / P>
< P>麦格纳aliquam ERAT volutpat。 。UT WISI enim广告微量veniam< / P>我能想到的一些方法可以做到这一点:
- 修改控制器中的文字(虽然我preFER避免修改我的模型)
- 在链接功能使用的指令,并产生第(似乎过于繁琐)。
- 使用过滤器(我目前最喜欢的)来创建一个数组来管进入NG-重复
解决方案我能想到的最好的解决方案是创建一个过滤器:
angular.module('对myApp')。
过滤器('nlToArray',函数(){
复位功能(文本){
返回text.split('\\ n');
};
});这需要一个文本块,并为每个段落创建一个新的数组元素。
这阵列可以被插入到NG-重复指令:
< p NG重复=段落文本块| nlToArray轨道由$指数> {{}段}< / P>
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:
- Modify the text in the controller (though I prefer to avoid modifying my models)
- Using a directive, and generating paragraphs in a link function (seems overly cumbersome).
- Using a filter (my current favourite) to create an array to pipe into ng-repeat
解决方案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>
这篇关于AngularJS:换行符为段落元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!