我正在通過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