I'm learning angular by making a browser-based Sudoku solver. There are many ways to solve my problem, but I'm looking for the most angular way to do it.
My html creates a 9x9 grid of text inputs, using a nested ng-repeat. The behavior that I'm looking to achieve is this: after a user enters a number into a text input (which uses a directive called "grid-cell"), an onBlur event will fire and the number will be added to the controller's 9x9 array (identified in the controller as $scope.grid, which initializes as an array of arrays of nine empty strings)
My html looks like this. I feel reasonably good about it:
<div ng-controller="SudokuController">
<table>
<tr ng-repeat="row in dimension">
<td ng-repeat="col in dimension">
<grid-cell row="{{ row }}" col="{{ col }}"></div>
</td>
</tr>
<tr>
<td id="submit" colspan="9">
<button ng-click="submit()" id="submit">Submit</button>
</td>
</tr>
</table>
</div>
My angular code looks like this (I don't feel like I should need much more than a single controller and a directive):
var app = angular.module('app',[]);
app.controller('SudokuController', function($scope) {
$scope.dimension = [1,2,3,4,5,6,7,8,9];
$scope.grid = [];
for (var i = 1; i<=$scope.dimension.length; i++) {
$scope.grid[$scope.grid.length] = ['','','','','','','','',''];
}
$scope.addNumber = function(row, col, val) {
$scope.grid[row][col] = val; // I would like it to work this way
};
$scope.submit = function() {
// insert sudoku-solving algorithm here
};
});
app.directive('gridCell', function() {
return {
restrict: "EA",
template: '<input type="text" />',
replace: true,
scope: {
row: '@',
col: '@'
},
link: function(scope, elem, attrs) {
elem.bind('blur', function() {
//how do I correctly write this?
scope.addNumber(scope.row, scope.col, elem[0].val);
});
}
}
});
This does not work; using elem.bind() in link on the directive can't seem to talk to the controller. However, I'm not even sure if this is even the "right" way to approach it. I am also wondering if I should be doing something like this:
<td ng-repeat="col in dimension">
<grid-cell row="{{ row }}" col="{{ col }}" ng-blur="addNumber(row, col, getThisValueSomehow)"></div>
</td>
Thanks in advance.