@@ -14,66 +14,69 @@ no connection between the controller and the view.
1414<doc:example>
1515 <doc:source>
1616 <script>
17- function TicTacToeCntl($location){
18- this.$location = $location;
19- this.cellStyle= {
17+ function TicTacToeCntl($scope, $location) {
18+ $scope.cellStyle= {
2019 'height': '20px',
2120 'width': '20px',
2221 'border': '1px solid black',
2322 'text-align': 'center',
2423 'vertical-align': 'middle',
2524 'cursor': 'pointer'
2625 };
27- this.reset();
28- this.$watch('$location.search().board', this.readUrl);
29- }
30- TicTacToeCntl.prototype = {
31- dropPiece: function(row, col) {
32- if (!this.winner && !this.board[row][col]) {
33- this.board[row][col] = this.nextMove;
34- this.nextMove = this.nextMove == 'X' ? 'O' : 'X';
35- this.setUrl();
36- }
37- },
38- reset: function() {
39- this.board = [
26+
27+ $scope.reset = function() {
28+ $scope.board = [
4029 ['', '', ''],
4130 ['', '', ''],
4231 ['', '', '']
4332 ];
44- this.nextMove = 'X';
45- this.winner = '';
46- this.setUrl();
47- },
48- grade: function() {
49- var b = this.board;
50- this.winner =
33+ $scope.nextMove = 'X';
34+ $scope.winner = '';
35+ setUrl();
36+ };
37+
38+ $scope.dropPiece = function(row, col) {
39+ if (!$scope.winner && !$scope.board[row][col]) {
40+ $scope.board[row][col] = $scope.nextMove;
41+ $scope.nextMove = $scope.nextMove == 'X' ? 'O' : 'X';
42+ setUrl();
43+ }
44+ };
45+
46+ $scope.reset();
47+ $scope.$watch(function() { return $location.search().board;}, readUrl);
48+
49+ function setUrl() {
50+ var rows = [];
51+ angular.forEach($scope.board, function(row) {
52+ rows.push(row.join(','));
53+ });
54+ $location.search({board: rows.join(';') + '/' + $scope.nextMove});
55+ }
56+
57+ function grade() {
58+ var b = $scope.board;
59+ $scope.winner =
5160 row(0) || row(1) || row(2) ||
5261 col(0) || col(1) || col(2) ||
5362 diagonal(-1) || diagonal(1);
5463 function row(row) { return same(b[row][0], b[row][1], b[row][2]);}
5564 function col(col) { return same(b[0][col], b[1][col], b[2][col]);}
5665 function diagonal(i) { return same(b[0][1-i], b[1][1], b[2][1+i]);}
5766 function same(a, b, c) { return (a==b && b==c) ? a : '';};
58- },
59- setUrl: function() {
60- var rows = [];
61- angular.forEach(this.board, function(row){
62- rows.push(row.join(','));
63- });
64- this.$location.search({board: rows.join(';') + '/' + this.nextMove});
65- },
66- readUrl: function(scope, value) {
67+ }
68+
69+ function readUrl(scope, value) {
6770 if (value) {
6871 value = value.split('/');
69- this .nextMove = value[1];
72+ $scope .nextMove = value[1];
7073 angular.forEach(value[0].split(';'), function(row, col){
71- this .board[col] = row.split(',');
72- }, this );
73- this. grade();
74+ $scope .board[col] = row.split(',');
75+ });
76+ grade();
7477 }
7578 }
76- };
79+ }
7780 </script>
7881
7982 <h3>Tic-Tac-Toe</h3>
0 commit comments