Search code examples
angularjsangularjs-ng-model

How use multiply ng-models in AngularJS


I have textarea with ng-model 'wordset' and ng-change="onChange()"

<div>
    <textarea ng-model="wordset" ng-change="onChange()"
              class="form-control app-word-set"
              placeholder="Enter Word Set" rows="4">
    </textarea>
</div>

I have button which added new textarea in this div. I needed that already added textarea includes the same on change method that my first textarea i have. But it should use ng-model... I want to use on method in my angularJS controller that gets values from every textarea by foreach like this:

$scope.wordSetTextarea = angular.element(document.getElementsByClassName('app-word-set'));

$scope.onChange = function() {
angular.forEach($scope.wordSetTextarea, function(value, key) {
      console.log(value);
   });
}

Is this possible?


Solution

  • With the AngularJS framework, multiple elements are added with the ng-repeat directive:

    <div ng-repeat="item in itemArr">
        <textarea ng-model="item.wordset"
                  ng-change="onChange(item,$index)"
                  name="'item' + $index"
                  class="form-control app-word-set"
                  placeholder="Enter Word Set" rows="4">
        </textarea>
    </div>
    
    <button ng-click="addNewTextarea()">Add input</button>
    
    $scope.itemArr = [{}];
    
    $scope.addNewTextarea = function() {
        $scope.itemArr.push({});
    };
    

    New AngularJS developers often do not realize that ng-repeat, ng-switch, ng-view, ng-include and ng-if all create new child scopes, so [data hiding problems] often shows up when these directives are involved ... [they] can be easily avoided by following the "best practice" of always have a '.' in your ng-models.

    For more information, see