fix database name in view
[angular-mojolicious.git] / templates / Cookbook / 4-MVC.html.ep
1 <script>
2 function TicTacToeCntl(){
3   this.cellStyle= {
4     'height': '20px',
5     'width': '20px',
6     'border': '1px solid black',
7     'text-align': 'center',
8     'vertical-align': 'middle',
9     'cursor': 'pointer'
10   };
11   this.reset();
12   this.$watch('$location.hashPath', this.readUrl);
13 }
14 TicTacToeCntl.prototype = {
15   dropPiece: function(row, col) {
16     if (!this.winner && !this.board[row][col]) {
17       this.board[row][col] = this.nextMove;
18       this.nextMove = this.nextMove == 'X' ? 'O' : 'X';
19       this.setUrl();
20     }
21   },
22   reset: function(){
23     this.board = [
24       ['', '', ''],
25       ['', '', ''],
26       ['', '', '']
27     ];
28     this.nextMove = 'X';
29     this.winner = '';
30     this.setUrl();
31   },
32   grade: function(){
33    var b = this.board;
34    this.winner =
35     row(0) || row(1) || row(2) ||
36     col(0) || col(1) || col(2) ||
37     diagonal(-1) || diagonal(1);
38    function row(r) { return same(b[r][0], b[r][1], b[r][2]);}
39    function col(c) { return same(b[0][c], b[1][c], b[2][c]);}
40    function diagonal(i) { return same(b[0][1-i], b[1][1], b[2][1+i]);}
41    function same(a, b, c) { return (a==b && b==c) ? a : '';};
42   },
43   setUrl: function(){
44     var rows = [];
45     angular.foreach(this.board, function(row){
46       rows.push(row.join(','));
47     });
48     this.$location.hashPath = rows.join(';') + '/' + this.nextMove;
49   },
50   readUrl: function(value) {
51     if (value) {
52       value = value.split('/');
53       this.nextMove = value[1];
54       angular.foreach(value[0].split(';'), function(row, i){
55         this.board[i] = row.split(',');
56       }, this);
57       this.grade();
58     } else {
59       this.reset();
60     }
61   }
62 };
63 </script>
64 <h3>Tic-Tac-Toe</h3>
65 <div ng:controller="TicTacToeCntl">
66 Next Player: {{nextMove}}
67 <div ng:show="winner">Player {{winner}} has won!</div>
68 <table>
69   <tr ng:repeat="row in board" style="height:15px;">
70     <td ng:repeat="cell in row" ng:style="cellStyle" 
71             ng:click="dropPiece($parent.$index, $index)">{{cell}}</td>
72   </tr>
73 </table>
74 <button ng:click="reset()">reset board</button>
75 </div>