Append selected list elements into textarea, add own text

1.9k views Asked by At

On the basis of this post : Angularjs select elements from list and display in textarea

I would like to add functionality :

  1. Fill textarea on the basis of chosen elements from the list.
  2. Add additional text inserted by user -> when user decides that he/she wants to add element from the list (some data is written in textarea), select element from the list and "append" to existing text instead of "clear" all textarea and insert values from the list

Could you be so kind and explain me how should I do this ?

1

There are 1 answers

3
chris On BEST ANSWER

Here's a working jsfiddle doing what you ask. Every time you click on a list element it is appended to the textarea.

The main function is a generic directive that you can reuse across controllers:

myApp.directive('txtArea', function() {
    return {
        restrict: 'AE',
        replace: 'true',
        scope: {data: '=', model: '=ngModel'},
        template: "<textarea></textarea>",
        link: function(scope, elem, attrs) {
            scope.$watch('data', function(newVal, oldVal) {
                if (newVal) {
                    scope.model += JSON.parse(newVal[0])[attrs.property];
                }
            });
        }
    };
});

To use the directive, insert the following in your HTML (at the proper location - see jsfiddle):

<txt-area data="myModel" property="mail" placeholder="expected value" ng-model='model' ng-trim='false'></txt-area>
  • data myModel is the selection data from the select list, as before.

  • property mail is the property to use for extracting values from selected element.

  • model holds the textarea's content, which you can reuse as you like in your app.

Here's the complete relevant HTML code:

<div ng-app='myApp'>
    <div ng-controller="Main">            
        <p>Original</p>
        <select multiple="multiple" ng-model="myModel">
          <option ng-repeat="d in data" value="{{d}}">{{d.mail}}</option>
        </select>

        <txt-area data="myModel" property="mail" placeholder="expected value" ng-model='model' ng-trim='false'></txt-area>

        <div>{{model}}</div>
    </div>
</div>

Here's the controller and app sections:

var myApp = angular.module('myApp', []);

myApp.controller('Main', function($scope){
    $scope.data = [{mail:"a@foo"},{mail:"b@foo"},{mail:"c@foo"}];
    $scope.model = "";
});

Make sure that you define/initialise each directive's model (e.g. $scope.model = "") as above, otherwise it will appear as initially undefined.