Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I generate an array from each line of a textarea with AngularJS

Tags:

angularjs

I'm attempting to create a textarea who's input is bound to a JS array where entries correspond to each line in the text area.

I've been attempting to use ngList with it's optional parameter to specify the delimiter. I can make it work with the default (,) by adding a comma after each line of the textarea, but I really do not want to require that.

the textarea

<textarea ng-model="list"
          rows="5"
          ng-list="\n" >
</textarea>

with the input:

test1
test2
test3

The generated output is ["test1\ntest2\ntest3"]

What I am looking for is: ["test1","test2",test3"]

Plnkr Demo

like image 528
Zach Lysobey Avatar asked Apr 08 '14 15:04

Zach Lysobey


3 Answers

This was updated in Angular 1.3 and now works like this:

<textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  • add ng-trim="false" directive to the <textarea> tag
  • use the ASCII code for newline character: &#10;
like image 70
OrangeSalty Avatar answered Nov 05 '22 22:11

OrangeSalty


EDIT: As of Angular 1.3, this answer is obsolete.

Please refer to @OrangeSalty's answer


From the (1.2) ngList docs:

If specified in form /something/ then the value will be converted into a regular expression.

I just added the /'s and it magically worked!

<textarea ng-model="list"
          rows="5"
          ng-list="/\n/" >
</textarea>

updated plnkr demo

like image 42
Zach Lysobey Avatar answered Nov 06 '22 00:11

Zach Lysobey


You could split the output angular gives you:

var result = ["test1\ntest2\ntest3"][0].split("\n")

// result = ["test1", "test2", "test3"]

(Although the solution you've posted is much better!)

like image 2
Chris Charles Avatar answered Nov 05 '22 22:11

Chris Charles