I want to create multiple input fields in a for-loop and assign a unique ng-model name to each field so I can use the values later.
Here is how I did it. inputmap is a map.
<script cam-script type="text/form-script">
for (let i=0;i<3;i++){
var name = "inputmap.item"+ i.toString(); // inputmap.item0, inputmap.item1, inputmap.item2, etc
document.getElementById("inputs").innerHTML += "<input type='text' ng-model='" + name + "' required/><br>"
}
</script>
<div id="inputs"></div>
But when I look at the $scope.inputmap, it's empty.
When I hardcode the input fields like:
<div id="inputs">
<input type='text' ng-model='inputmap.item0' required/><br>
<input type='text' ng-model='inputmap.item1' required/><br>
<input type='text' ng-model='inputmap.item2' required/><br>
</div>
I was able to get the values I entered in the fields. I am new to HTML and any help/hints is appreciated.
First you have += on document.getElementById("inputs").innerHTML += "<input type='text' ng-model='" + name + "' required/><br>" and can be changed to just =
There are to ways to do this. I think if you change document.getElementById("inputs").innerHTML += "<input type='text' ng-model='" + name + "' required/><br>" to document.getElementById("inputs").innerHTML = `<input type='text' ng-model="${name}" required/><br>` then that will add it in correctly. Never done this though and might not work where you can do my second way of doing it:
for(let i = 0; i < 3; i++) {
let input = document.createElement('input') //Creates input element
let wrapper = document.getElementById('inputs') //Gets the div element
let name = `inputmap.item${i.toString()}` //Gets the name
input.setAttribute('ng-model', name) // Sets 'ng-model' attribute to name
wrapper.appendChild(input) //Sets 'wrapper' as 'input' parent
}
Hope this helps!