2016-03-17 51 views
0

我想問你想要多少選擇?如果用戶輸入10,則應顯示10個選項。我努力嘗試,但這是給內存錯誤。Angularjs獲取字段數

dynamicform.jsp

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

<script data-require="[email protected]" data-semver="3.3.2" src="js/bootstrap.min.js"></script> 

<script data-require="[email protected]" data-semver="2.1.3" src="js/jquery-2.1.3.min.js"></script> 

- >

動態表單字段創建插件

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

};

}); 

錯誤

了內存

+0

請分享一個小提琴或plunker –

回答

1

這看起來像for循環將會繼續,而i小於$scope.choices.length + nochoices

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}); 
} 
+0

錯誤:選擇是未定義 [email protected]://本地主機:8083 /例1/JS/angularjs/1.4.8/app.js:53:6 $ parseFunctionCall @ http:// localhost:8083/example1/js/angularjs/1.3.15/angular.js:12404:15 $ RootScopeProvider/this。$ get

+0

嗯 - 不確定。但我敢打賭,你把它放在一個普朗克或jsfiddle中,有人會在幾分鐘內解決這個問題。而且很有可能你會在這個過程中解決它:) –

+0

https://jsfiddle.net/gyoLhxq2/ –