0

I have to loop through an array of objects and display the values in textarea. Below is the code i tried so far:

<body ng-controller="testCtrl">
<div class="container" ng-repeat="i in items">
    <div class="containerDescription">
        <textarea ng-model="i.name" 
          style="height:120px; width:200px;"></textarea><br>

    </div>

The values are getting displayed in different textareas. How to display the values in the same textarea?Attached the plunkr link : http://plnkr.co/edit/DF2Na5vHd9SKu9MHQFvb?p=preview

1
  • I'm not too familiar with Angular, but given your setup and behavior I'd assume that your loop is making a new instance of textarea based on your ng-model parameter. Would it work correctly if you moved the parameter to a element inside your textarea like <textarea><p ng-model="i.name"></p></textarea>? Commented Jan 9, 2019 at 18:20

2 Answers 2

2

You do not need ng-repeat here, you could join all the elements with the folliwing and call the function

$scope.textAreaValues = function() {
    return $scope.items.map(function(elem) {
      return elem.name;
    }).join("\n");
 }

PLUNKER DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

Hi Saneetharan thanks for the solution.Instead of comma is there a way that i can display the values in the next line?
1

Should you want to take advantage of two-way data binding, so that users entered manually into the textarea would appear in your model, then you may use a directive with custom $formatter and $parser (to match your data structure):

angular.module('demo').directive('formatNames', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attr, ctrl) {
      ctrl.$formatters.push(function(users) {
          return users.map(function(user) {
            return user.name;
          }).join('\n')
      });
      ctrl.$parsers.push(function(users) {
          return users.split('\n').map(function(name, i) {
            return { id: i, name: name };
          });
      })
    }
  }
});

http://plnkr.co/edit/9zXCyOUYjiRuIwcFwypz?p=preview

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.