嵌套的 ng-repeat 不会更新对象

Nested ng-repeat doesn't update object

本文关键字:更新 对象 ng-repeat 嵌套      更新时间:2023-09-26

我需要向用户预设NxN矩阵输入。 因此,我在表对象上使用嵌套的 ng-repeat 来创建输入。 尽管它最初成功填充,但它不会更新对象。

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

ng-model需要引用对象(数组)的实际部分,而不仅仅是值。

ng-model="Row[$index]"

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

否则,它不会更新实际对象的引用。假设您正在循环访问一个数组,并且您只是修改值,而不是数组中的引用:

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

^ ng-repeat ng-model其中一个值的行为方式相同。

注意:使用<input type="number" ... />否则您的ng-model值将变成字符串!

更改

<input type="text" ng-model="I">

<input type="text" ng-model="Row[$index]">

分叉你的 JSFiddle