9

I have a angularJS application, in which I have an array.

  $scope.data[0] =  x1;
  $scope.data[1] =  x2;

and a text area

  <textarea ng-model="data"> </textarea>

I can see the that textarea contains values x1, x2 (separated by comma). I want to show the values on separate lines. Meaning all array values should be separated by new line character not by comma. Do I need to write filter for this?

Shamaila Tahir
  • 988
  • 2
  • 8
  • 17

3 Answers3

16

This is exactly what ng-list does:

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

This also works on all other kinds of inputs as it hooks into ngModels parsers/formatters.

See this fiddle: http://jsfiddle.net/xbYzT/1/

The problem with this is that ng-list always joins with a ',' as the separator, so it's not really bi-directional.

Martin Probst
  • 9,497
  • 6
  • 31
  • 33
  • 1
    The only problem with this is that `ngList` always joins an existing array with `, ` as the separator, ignoring the user-selected separator - even if it is not a regex. – T Percival Feb 26 '14 at 22:29
  • Ted: yes, that's an ugly issue - and it's not easy to fix as you cannot really revert splitting by regexp. Updated the comment to reflect that. – Martin Probst Feb 27 '14 at 17:38
  • 1
    AngularJS 1.3 is removing support for regexes in ngSplit, making it a moot point. – T Percival Feb 27 '14 at 22:57
16

A much easier way to do this in Angular >= 1.3 which works both ways:

<textarea ng-model="yourStringArray" ng-list="&#10;" ng-trim="false"></textarea>

Plunker

Saeb Amini
  • 23,054
  • 9
  • 78
  • 76
15

You can write a directive that modifies how ng-model converts variables into input values and back. I'm just writing this off the top of my head, so I have no idea if it's exactly right, but something like this might do it:

app.directive('splitArray', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attr, ngModel) {

            function fromUser(text) {
                return text.split("\n");
            }

            function toUser(array) {                        
                return array.join("\n");
            }

            ngModel.$parsers.push(fromUser);
            ngModel.$formatters.push(toUser);
        }
    };
});

And you can use it like this:

  <textarea ng-model="data" split-array> </textarea>
gligoran
  • 3,267
  • 3
  • 32
  • 47
Karen Zilles
  • 7,633
  • 3
  • 34
  • 33
  • 1
    You can look to this answer for more examples of formatters and parsers: http://stackoverflow.com/questions/11616636/how-to-do-two-way-filtering-in-angular-js – Karen Zilles Jul 11 '13 at 06:24