简体   繁体   中英

Angularjs Passing Factory Objects Between Controllers

Perhaps I'm using angular factories incorrectly, but I'm writing code in an object-oriented fashion to create things I need and I'm trying to figure out how to go about passing the created objects between controllers.

I'm aware that factories are "singletons", so injecting the factory into each controller should do the job.. However, my confusion is more clear if I show you my code.

In services.js

.factory('Game', function () {
    var Game = function (name, description) {
        this.name = name;
        this.description = description;
        this.rating = 0;
        this.rooms = [];
    }

    return Game;
})

So here I define the constructor for a "Game" object.

And in my controllers.js, where I create 2 test game objects

.controller('CreateCtrl', function ($scope, Game) {
    var game1 = new Game("Test Adventure!", "An amazing adventure to do some cool things and such!");
    var game2 = new Game("Test Adventure 2!", "An amazing adventure to do some cool things and such!");

    $scope.games = [game1, game2];
})

I inject the "Game" factory into the controller, and define two "Game" objects with the "new" keyword. Two questions come up.. 1) How is a factory a singleton when I can create multiple objects? And 2) How can I pass both game1 and game2 into another controller?

Maybe I'm confused with object-oriented programming in angularjs, and am creating my game objects incorrectly.

Please help!

Edit: I believe a simple solution would be to use $rootScope to hold the data objects, but I don't think that this is the standard way to go about doing things? It seems developers urge to avoid using rootScope..

I think you are mistaking the factory/service (which is a data manager) with the actual class of data that you are wanting to manage. The manager should ideally return an object representing the public functions or data that it exposes. Here is an example

.factory('GameManager', function() {
    var _games = [];

    var Game = function (name, description) {
        this.name = name;
        this.description = description;
        this.rating = 0;
        this.rooms = [];
    };

    function createGame(name, description) {
        _games.push(new Game(name, description));
    }

    return {
        games: _games,
        createGame: createGame
    };
});

and in the controller:

GameManager.createGame('asdf', 'asdf');

or

GameManager.games...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM