I'm working on a form where user input determines the number of additional input boxes created. Below is the JavaScript code used for this functionality.
for(i = 1; i <= c; i++) { //c = total input count
block = block + '<div class="row">'+
'<div class="form-group col-lg-12">'+
'<input id="name" ng-model="new.var'+i+'name" type="text" class="form-control">'+
'<input id="type" ng-model="new.var'+i+'type" type="text" class="form-control">'+
'</div>'+
'</div>';
}
document.getElementById("vars").innerHTML = block;
The above code successfully generates dynamic ng-model variables like
new.var1name, new.var1type, new.var2name, new.var2type
, and so on.
However, I am facing difficulties accessing these variables in my controller. When trying to create them manually in the controller, an error occurs stating that 'name' cannot be found.
var var1 = [];
for(i = 1; i <= c; i++) { //c = total input count
var item = {};
console.log('var'+i+'name', 'var'+i+'unit');
item['name'] = $scope.new.var+i+name;
item['type'] = $scope.new.var+i+type;
var1.push(item);
}
console.log(JSON.stringify(var1));
To resolve this issue, I have modified the code as follows, but now the var1 array remains empty without any errors.
var var1 = [];
for(i = 1; i <= c; i++) {
var item = {};
console.log('var'+i+'name', 'var'+i+'type');
item['name'] = $scope.new['var'+i+'name'];
item['type'] = $scope.new['var'+i+'type'];
var1.push(item);
}
console.log(JSON.stringify(var1));
If anyone can assist me in identifying what I am doing wrong or if this approach is feasible, it would be greatly appreciated.