Ad

How To Add Textarea Input Dynamically By Input Number Value? AngularJs

I have a number inputtext to user input the number of fields(textarea inputs) he wants to fill:

<input type="number" class="form-control" min="1" max="4" value="1">


<div ng-repeat="...">
   <div class="form-group">
        <textarea class="form-control" rows="3"></textarea>
   </div>
</div>

</div>

Is there something like a simply for (for var = 1 to 5, for example) for AngularJs ng-repeat or similar way to do it easily?

Ad

Answer

angular.module("demo", [])
  .controller("DemoCtrl", function($scope) {

    $scope.itemCount = 1;

    $scope.items = [];

    $scope.onItemCountChanged = function() {

      // Remove items if needed
      if ($scope.itemCount < $scope.items.length) {
        $scope.items = $scope.items.slice(0, $scope.itemCount - $scope.items.length);
        return;
      };

      // Add items if needed
      if ($scope.itemCount > $scope.items.length) {
        var numberToAdd = Math.abs($scope.items.length - $scope.itemCount);
        for(var i = 0; i < numberToAdd; i++) {
          $scope.items.push({ text: "item text" });
        }
      }
    };
  });

And here's a view

<div ng-app="demo" ng-controller="DemoCtrl">
  <input type="number" min="1" max="4" ng-model="itemCount" ng-change="onItemCountChanged()" />

  <div ng-repeat="item in items track by $index">
    <textarea ng-model="item.text"></textarea>
  </div>

</div>
Ad
source: stackoverflow.com
Ad