Values are duplicated into all input field which is created using the ng-repeat and ng-model

1.2k Views Asked by At

I am using the ng-repeat to create the input fields dynamically, everything seems to be working fine and the input fields are created but due to some reason when I enter some value into that created input field then due to two-way data binding the value is entered simultaneously in all the text fields that were created.

As per my knowledge, I am assigning the different ng-model to each of the created fields so I am not sure why the values are being copied. When I try to print the values which are assigned to the input field just above the field then I see the id is different wanted to know why all the fields are taking the same value and also how can I prevent it.

HTML Code:

<tr>
    <td ng-repeat="extension in ExtensionList">
        <!-- Here the value displayed are different -->
        {{ formdata.extension.ExtensionVlaues }}
        <input type="text" class="form-control" id="extension.ExtensionVlaues" ng-model="formdata.extension.ExtensionVlaues">
    </td>
</tr>

Here is the screenshot from the front-end: enter image description here

Here is the example of my ExtensionList: {"Field1":"","Field2":"","Field3":1,"ExtensionVlaues":2}

As per my knowledge, the given ng-model is different but still not working. Can anyone please help me with this? I tried few things like ng-model="formdata.extension[ExtensionVlaues]" but still no luck.

I tried to assign ng-model like this but it is not working:

  1. ng-model="formdata.extension[ExtensionVlaues]"

Based on the below answer I tried 2 different things it but it's not working and getting the same issue. Please let me know how can I resolve this:

<td ng-repeat="(key, extension) in ExtensionList">
    <input type="text" ng-model="formdata.extension.key">
</td>

<td ng-repeat="(key, extension) in ExtensionList">
    <input type="text" ng-model="formdata.extension.ExtensionVlaues">
</td>
2

There are 2 best solutions below

3
h01001000 On BEST ANSWER

You are trying to use ExtensionList as an array. You need to use it as an object with ng-repeat:

<td ng-repeat="(key, extension) in ExtensionList">
    <input type="text" ng-model="formdata[extension][key]">
</td>

<td ng-repeat="(key, extension) in ExtensionList">
    <input type="text" ng-model="formdata[extension][ExtensionVlaues]">
</td>
0
BATMAN_2008 On

Just incase anyone else also struck at this issue:

<span ng-repeat="(key, extension) in ExtensionList" class="form-inline">
    <br/>                                       
    <span>
        {{ extension.NameSpace + ":" + extension.LocalName }}
    </span>&ensp;
    <input type="text" class="form-control" id="extension.ExtensionVlaues" ng-model="ExtensionList.extension[key].FreeText" ng-blur="ExtensionText(ExtensionList.extension[key].FreeText, extension.ExtensionVlaues)">
</span>