如何通过输入数值动态添加textarea输入? AngularJs

时间:2016-03-23 01:04:48

标签: javascript angularjs angularjs-directive angularjs-ng-repeat

我有一个数字输入文本,用户输入他想要填写的字段数(textarea输入):

<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>

对于AngularJs ng-repeat或类似的方法,是否有类似简单的for(对于var = 1到5)这样的东西很容易做到?

1 个答案:

答案 0 :(得分:1)

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" });
        }
      }
    };
  });

这是一个观点

<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>