Zak Kus
Zak Kus

Reputation: 1513

Angularjs: Printing an Array model with new lines in a TextArea

I have a simple textarea control,

<div ng-controller="TodoCtrl">
      <textarea ng-model="myArray"></textarea>
  </div>

and a model that is an array of strings:

function TodoCtrl($scope) {
  $scope.myArray = [
      "something1", 
      "something2",
      "something3",
   ];    
}

Im trying to get it so that every entry is on its own line:

something1 
something2
something3

And for extra credit would like to resplit the text back into an array on hte model side.

I've tried a few things, including ng-list, custom directives, custom filters, and ng-repeat, but haven't gotten any where.

fiddle Example:

http://jsfiddle.net/U3pVM/8162/

Upvotes: 1

Views: 3490

Answers (2)

alexrogers
alexrogers

Reputation: 1584

What you want is to have two vars. Essentially your textarea is a text string. So if you need an array then set up a watcher on the string model.

http://jsfiddle.net/U3pVM/8165/

$scope.myStr = 'aaaa\nbbbb\nccccc';
$scope.$watch('myStr', function(myStr){
    $scope.myArray = myStr.split('\n');
    console.log('$scope.myArray', $scope.myArray);
});

Upvotes: 1

alexrogers
alexrogers

Reputation: 1584

I'm not sure I understand what you're trying to achieve. There is no textarea in the fiddle.

You can doctor your array to have new line characters at the end of each string. Not sure if that helps?

$scope.myArr = ['111\n', '222\n', '333\n']

http://jsfiddle.net/U3pVM/8161/

Your fiddle has quite a lot of info in, maybe make it simpler? Showing input and output.

Edit:

Is it for input and output? If just for output, you could just do something like this: http://jsfiddle.net/U3pVM/8164/

Upvotes: 1

Related Questions