Search code examples
angularjsangular-ngmodelangularjs-ng-model

Iterating ng-model? Is it possible?


I would like to make a loop that can be automatically initiated at first empty values in the input and then complement them consecutively. However, I do not know how to do it in angularjs using ng-model. Well, I have a html file

<input type="text" id="pin" ng-model="inputData.pin" />
 <input type="text" id="pin2" ng-model="inputData.pin2" />

And I would controller instead of writing

$scope.inputData = { pin : '' };
$scope.inputData = { pin2 : '' };

for automatic loop

for (var key in receivedData) {
                for (var detailKey in receivedData[key]) {
                    $scope.inputData = { detailKey : '' };
                }
            }

when detailKey is in sequence pin, pin2.

Currently, this does not work. Does anyone know how to do it? Thanks in advance for your help :)


Solution

  • It looks like you have misunderstood how to assign a value to an object -- you must treat it like an associative array.

    In your example you are redefining the entire property $scope.inputData within each iteration by giving it an object literal that has a single key detailKey whose value is an empty string ('').

    What you instead want to do is define a new property on the object, not 'overwrite' the object itself:

    for (var key in receivedData) {
        for (var detailKey in receivedData[key]) {
            $scope.inputData[detailKey] = '';
        }
    }
    

    You can then iterate through the keys represented in this object within your Angular template using the ng-repeat directive, taking each key from inputData and binding their value to an <input> element. This will create n <input> elements where (n === Object.keys(inputData).length).

    <input type="text" class="pin"
           ng-repeat="key in inputData"
           ng-model="inputData[key]" />
    

    Note: you cannot have an ID that is used more than once within the same document. I have changed each <input> element to have a class 'pin' instead.