The scenario is a Sudoku game with JavaScript and AngularJS.
The Sudoku field is an Array (rows) of Arrays (columns). All arrays have a length of 9. I name this Sudoku field matrix
. The function exampleMatrix()
returns such a matrix which already has some fields filled.
An updateValue(sudokuMatrix, row, col, val)
function changes the field at position row row
and column col
in the matrix sudokuMatrix
to the value val
.
function TestController($scope) {
$scope.matrix = exampleMatrix();
$scope.updateValue = updateValue;
$scope.getMatrixVal = function getMatrixVal(row, col) {
return $scope.matrix[row][col];
};
}
What I want to do is to display every field of the matrix as an <input type="text">
field in HTML. I want all the fields to be initially set to the values they have in the matrix. If the input of a text field is changed, I want the value to be updated in the $scope.matrix
object.
I can fill the fields with the values of the matrix with no problem with the following HTML/AngularJS Code:
<div ng-repeat="(rowIndex,row) in matrix track by $index">
<input type="text" size="1" value="{{col}}"
ng-repeat="(colIndex,col) in row track by $index">
</div>
But I cannot update the values in the $scope.matrix
object yet, of course.
The problems I am facing are
- If I change the value in an input field, the
matrix
should update that value. I can do this withng-change="updateValue(matrix, rowIndex, colIndex, inputVal)"
. - In order to be able to change the
matrix
in the scope withng-change
, I need anng-model
, which binds the input of the field to a variable:ng-model="inputVal"
- If I add those two lines, the input fields are not filled initally with the values in the
matrix
object of the scope.
The current code looks like this:
<div ng-repeat="(rowIndex,row) in matrix track by $index">
<input type="text" size="1" value="{{getMatrixVal(rowIndex, colIndex)}}"
ng-model="inputVal"
ng-change="updateValue(matrix, rowIndex, colIndex, inputVal)"
ng-repeat="(colIndex,col) in row track by $index">
</div>
My guess is that when the site is generated, ng-model
assigns the empty value of the input field to inputVal
, and that ng-change
is immediately triggered. Every field of the matrix would thus be populated with an empty value. AngularJS is not throwing any errors though, so I cannot be sure. Anyways, I'm at a loss here and do not know how to get the initial values to be written to the fields initially and ng-change
to be only called afterwards. I appreciate every help.
JSFiddle: https://jsfiddle.net/30xkedmp/
JavaScript: http://pastebin.com/8cge8BXs HTML: http://pastebin.com/X0YUPU4h