AngularJS:换行符为段落元素 [英] AngularJS: newline characters to paragraph elements

查看:193
本文介绍了AngularJS:换行符为段落元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在角,我需要从包含换行字符的文本块生成一系列段落元素的?

我能想到的几个方法可以做到这一点。但是我想知道是否有一个官方角方式,或只是最优雅的方式将是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&​​LT; / P>
&所述p为H.;桑达直径nonummy NIBH euismod tincidunt UT laoreet dolore&下; / P>
< P>麦格纳aliquam ERAT volutpat。 。UT WISI enim广告微量veniam< / P>

我能想到的一些方法可以做到这一点:


  1. 修改控制器中的文字(虽然我preFER避免修改我的模型)

  2. 在链接功能使用的指令,并产生第(似乎过于繁琐)。

  3. 使用过滤器(我目前最喜欢的)来创建一个数组来管进入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:

  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

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆