ng-model与2d数组绑定

时间:2015-12-26 20:12:17

标签: javascript arrays angularjs

请耐心等待我,因为我是棱角分明的新手。我的视图中有一个文本输入框网格,我希望映射到我的控制器中的2d数组或者java脚本中的奇怪的等效数组。我的观点中的代码是

<div ng-repeat="row in [1,2,3,4,5,6,7,8,9]" class="row">
                <div ng-repeat="column in [1,2,3,4,5,6,7,8,9]" class="col-sm-1 no-padding">
                    <input type="text" class="form-control" ng-model="puzzle.board[row][column]" name="cell[]">
                </div>
</div>

我的控制器类使用以下代码初始化拼图对象

    $scope.puzzle = {}; 
    $scope.puzzle.dimensions =9;
    $scope.puzzle.board = [$scope.puzzle.dimensions]
    for(var i=0; i<$scope.puzzle.dimensions; i++) {
            $scope.puzzle.board[i] = [$scope.puzzle.dimensions];
    }

但是,当我在输入字段中输入一个值并检查控制台中单元格的值时,它仍然显示为未定义 我在这里失踪了什么?

1 个答案:

答案 0 :(得分:2)

尝试:

  $scope.puzzle.board = [];

  for (var i = 0; i < $scope.puzzle.dimensions; i++) {
    $scope.puzzle.board[i] = [];
    for (var j = 0; j < $scope.puzzle.dimensions; j++) {
      $scope.puzzle.board[i][j] = 0;
    }
  }

并从0开始编号:

<div ng-repeat="row in [0,1,2,3,4,5,6,7,8]" class="row">
    <div ng-repeat="column in [0,1,2,3,4,5,6,7,8]" class="col-sm-1 no-padding">
        <input type="text" class="form-control" ng-model="puzzle.board[row][column]" name="cell[]">
    </div>
</div>