参考Angular Factory中的Initialize变量

时间:2015-11-03 01:42:02

标签: javascript angularjs

我想创建一个负责生成PlayerList的工厂,但是我在访问我在initialize函数中设置的变量时遇到了问题。代码是

app.factory("PlayerList", function(){

    // Define the PlayerList function
    var PlayerList = function() {

        this.initialize = function() {
            // create an array for our players
            var players = [];
        };

        this.add = function(player) {
            this.players.push(player);
        }

        this.remove = function(player) {
            if ( players.length > 0 )
            {
                this.players.splice(players.indexOf(player), 1);    
            }
        }

        this.initialize();
    };

    return (PlayerList);

});

我想在添加和删除方法中引用player数组,但我还没有定义。

2 个答案:

答案 0 :(得分:0)

var playerList =(function(){

var playerLists = {};

playerList.playerList = function(){

    this.initialize = function() {
        // create an array for our players
        var players = [];
    };

    this.add = function(player) {
        this.players.push(player);
    }

    this.remove = function(player) {
        if ( players.length > 0 )
        {
            this.players.splice(players.indexOf(player), 1);    
        }
    }

    this.initialize();
};

return playerLists;

})();

app.factory(" PlayerList",playerList.playerList);

答案 1 :(得分:0)

此处var players = [];initialize的本地变量,但您期望this.players.push(player);表示players应位于PlayerList范围内。

所以你的工厂应该看起来像

app.factory("PlayerList", function () {

    // Define the PlayerList function
    var PlayerList = function () {

        var self = this;

        this.players = [];

        this.initialize = function () {
            self.players = [];
        };

        this.add = function (player) {
            self.players.push(player);
            console.log(self.players);
        }

        this.remove = function (player) {
            if (self.players.length > 0) {
                self.players.splice(self.players.indexOf(player), 1);
            }
        }

        this.initialize();
    };

    return (PlayerList);
});