Search code examples
angularjsangularjs-ng-repeatangular-ngmodel

Angularjs binding updates all selects in ng-repeat


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'}]


Solution

  • 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.