Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested ng-repeat doesn't update object

I need to preset NxN matrix input to the user. Therefore, I am using nested ng-repeat on a table object to create the input. Although it initially populates successfully, it doesn't update the object.

HTML

<div ng-app="myApp" ng-controller="VibrationCtrl">
  <table>
    <tr ng-repeat="Row in Mi">
      <td ng-repeat="I in Row track by $index">
        <input type="text" ng-model="I">
      </td>
    </tr>
  </table>

  {{Mi}}
</div>

JS

var myApp = angular.module('myApp', []);

function VibrationCtrl($scope) {
  $scope.Mi = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
  ];
}

myApp.controller('VibrationCtrl', VibrationCtrl);

JsFiddle:

https://jsfiddle.net/wLhucx8b/2/

like image 742
DBordello Avatar asked Jan 19 '26 11:01

DBordello


1 Answers

ng-model needs to reference the actual part of the object (array), rather than simply the value.

ng-model="Row[$index]"

https://jsfiddle.net/wLhucx8b/4/

Otherwise it will not update the actual object's reference. Imagine you're looping through an array and you just modify the value, rather than the reference in the array:

collection.forEach(function (value, index) {
  value = '123'; // this won't actually change the original array
  collection[index] = '123' // this WILL
});

^ ng-repeat with an ng-model on one of the values behaves the same way.

Note: Use <input type="number" ... /> or else your ng-model values will turn into strings!

like image 197
Atticus Avatar answered Jan 21 '26 00:01

Atticus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!