0

When I'm using ng-model inside of ng-repeat it updates all ng-models inside that repeat loop. If I remove datatype and directly set to myCtrl.data[$index] it works fine.

Any suggestions?

template:

<div ng-repeat="i in myCtrl.data track by $index">
   <div>
      <div>
         <select
            ng-model="myCtrl.data[$index].datatype"
            ng-options="item.value as item.label for item in myCtrl.detailTypes track by item.label"
         >
            <option value="" disabled selected>
               select an option
            </option>
         </select>
      </div>
   </div>
</div>

controller:

self.detailTypes = [
   {label: 'KEY_1', value: 'VAL_1'},
   {label: 'KEY_2', value: 'VAL_2'},
];

self.data = new Array(2).fill({dataType: null});

When I select KEY_1 for first select, it changes object to [{dataType: 'VAL_1'}, {dataType: 'VAL_1'}]

Ulfsark
  • 902
  • 1
  • 11
  • 26
  • I tried your code but could not reproduce this behavior when I used a function in ng-change for the selects populated in the ng-repeat. Does your template use only one controller? – Risalat Zaman Feb 17 '21 at 09:17
  • Weird but I found out the problem. I replace new Array(2).fill({dataType: null}); with push values in a loop. Problem is resolved. – Ulfsark Feb 17 '21 at 09:37

1 Answers1

1

Ok so this is happening because you are populating your self.data with Array.fill which when used with objects, passes by reference not value.

If you change declaration of your self.data to this

self.data = [];
self.data.push({dataType:null},{dataType:null});

it will work.

Risalat Zaman
  • 1,189
  • 1
  • 9
  • 19