AngularJS format array values in textarea

前端 未结 3 697
忘了有多久
忘了有多久 2021-01-02 08:28

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

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

and a text area

         


        
相关标签:
3条回答
  • 2021-01-02 09:12

    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>
    
    0 讨论(0)
  • 2021-01-02 09:15

    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

    0 讨论(0)
  • 2021-01-02 09:20

    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.

    0 讨论(0)
提交回复
热议问题