Angularjs得到的字段数

时间:2016-03-17 06:23:09

标签: javascript angularjs

我想问你想要多少选择?如果用户输入10,则应显示10个选项。我努力了,但这给了记忆错误。

dynamicform.jsp

 <!DOCTYPE html>
  <html ng-app="dynamicFieldsPlugin">
<head>
 <!--  <link data-require="bootstrap@3.3.2" data-semver="3.3.2" rel="stylesheet" href="themes/bootstrap.min.css" />

<script data-require="bootstrap@3.3.2" data-semver="3.3.2" src="js/bootstrap.min.js"></script>

<script data-require="jquery@2.1.3" data-semver="2.1.3" src="js/jquery-2.1.3.min.js"></script>

- &GT;                       

动态表单字段创建插件

  <label for="choice" ng-show="showChoiceLabel(choice)">Choices</label>

    <label>How many Choices you want?</label>
    <input type="text" ng-modal="{{nochoices}}" name="" value="{{nochoices}}">
    <button ng-show="showAddChoice(choice)" ng-click="addNewChoiceno(nochoices)">Add Choice</button>

  <div class="form-group" data-ng-repeat="choice in choices">
    <br/><br/>
    <!-- <button ng-show="showAddChoice(choice)" ng-click="addNewChoice()">Add Choice</button> -->

    <button ng-click="removeNewChoice()">Remove Choice</button>

    <input type="text" ng-modal="{{choice.name}}" name="" placeholder="Enter a restaurant name" value="{{choice.id}}">
  </div>
</div>
<!--jQuery Scripts -->
<script src="js/angularjs/1.4.8/app.js"></script>
</body>

app.js

  var app = angular.module("dynamicFieldsPlugin", []);

  app.controller("dynamicFields", function($scope) {


 $scope.nochoices = 10;
 $scope.choices = [{id: 'choice1', name: 'choice1'}];



 $scope.addNewChoice = function() {

 var newItemNo = $scope.choices.length+1;

 $scope.choices.push({'id' : 'choice' + newItemNo, 'name' : 'choice' + newItemNo});

};

  $scope.addNewChoiceno = function(nochoices) {


     for(var i=$scope.choices.length;i<nochoices+$scope.choices.length;i++){
     $scope.choices.push({'id' : 'choice' + i, 'name' : 'choice' + i});
     }
     $scope.choices.length=$scope.choices.length+nochoices;
   };

  $scope.removeNewChoice = function() {

 var newItemNo = $scope.choices.length-1;

 if ( newItemNo !== 0 ) {

  $scope.choices.pop();

 }

 };



 $scope.showAddChoice = function(choice) {

 return choice.id === $scope.choices[$scope.choices.length-1].id;

};

});

错误

内存不足

1 个答案:

答案 0 :(得分:1)

i小于$scope.choices.length + nochoices时,for循环似乎会继续

for(var i=$scope.choices.length;i<nochoices+$scope.choices.length;i++){
     $scope.choices.push({'id' : 'choice' + i, 'name' : 'choice' + i});
}

很遗憾,您正在推进循环中的$scope.choices 。这意味着如果i增长1,那么$scope.choices.length意味着循环条件将始终为真,循环将永远持续。

也许将上面的代码更改为:

for(var i=$scope.choices.length;i<nochoices;i++){
     $scope.choices.push({'id' : 'choice' + i, 'name' : 'choice' + i});
}