我正在通过ng-newsletter的2048游戏教程,我被困在未定义的gridservice方法上。angularjs服务中的方法未定义
下面是代码模块注入网格模块及其设置gridservice
angular.module('Game', ['Grid'])
.service('GameManager', ['GridService', function(GridService) {
// create a new game
this.newGame = function() {
GridService.buildEmptyGameBoard();
GridService.buildStartingPosition();
this.reinit();
};
}]);
这是我的网格模块和Gridserivce与方法的角度引用为被未定义沿着:
angular.module('Grid', [])
/**
* GridService handles all the conditions of the board
*/
.service('GridService', ['TileModel', function(TileModel) {
return {
buildEmptyGameBoard: buildEmptyGameBoard
}
this.startingTileNumber = 2;
// grid array acts the as the board and remains static
this.grid = [];
// tiles array acts the pieces on the board and will be dynamic
this.tiles = [];
this.tiles.push(new TileModel({x: 1, y: 1}, 2));
this.tiles.push(new TileModel({x: 1, y: 2}, 2));
// Size of the board
this.size = 4;
//this.buildEmptyGameBoard = function() {
function buildEmptyGameBoard() {
var self = this;
// Initialize our grid
for(var x = 0; x < this.size * this.size; x++) {
this.grid[x] = null;
}
// Initialize our tile array
// with a bunch of null objects
this.forEach(function(x,y) {
self.setCellAt({x:x, y:y}, null);
});
}
// Run a method for each element in the tiles array
this.forEach = function(cb) {
var totalSize = this.size * this.size;
for(var i = 0; i < totalSize; i++) {
var pos = this._positionToCoordinates(i);
cb(pos.x, pos.y, this.tiles[i]);
}
};
// Convert i to x,y
// cell position from single dimensional array
// converts to x and y coords for pos on game board
this._positionToCoordinates = function(i) {
var x = i % service.size;
y = (i - x)/service.size;
return {
x: x,
y: y
};
};
}])
/**
* TileModel Factory to define values for our tile directive css positions
*/
.factory('TileModel', function() {
var Tile = function(pos, val) {
this.x = pos.x;
this.y = pos.y;
this.value = val || 2;
};
return Tile;
});
Curretnly我我得到这个:错误:this.forEach不是一个函数
我已经能够解决在这个应用程序中的一些其他错误。所有的错误都是关于我的gridService中的方法没有被定义或不是一个函数。似乎是我的GridService中根本错误或缺失的东西,我无法看到。
注:这两个文件被调用,在我的index.html文件
非常感谢指针在这里我忘了自我=这项工作:所以你的代码更改。这解决了我的问题 – appthat 2014-09-19 21:02:28