Edx – AngularJS: Advanced Framework Technique

Module 1. Code

Using Factory Singletons
To use a Factory, first declare it on your Angular app.

myApp.factory('thisFactory', function(){
    
})
You then set properties of the object that the factory is going to return.

myApp.factory('thisFactory', function(){
    var factoryObject = {};
    factoryObject.food = 'Chicken';
    factoryObject.drink = 'Soda';
    factoryObject.getAll = function(){
        return factoryObject.food + ' ' + factoryObject.drink;
    }

    return factoryObject;

})
If you do not want to share state between components, return a new instance of the object instead:

myApp.factory('thisFactory', function(){
    var factoryObject = {};
    factoryObject.food = 'Chicken';
    factoryObject.drink = 'Soda';
    factoryObject.getAll = function(){
        return factoryObject.food + ' ' + factoryObject.drink;
    }

    return new factoryObject;

})
In order to use your factory in your controller or directive, declare it as a dependency:

myApp.controller('myController', ['thisFactory', function(thisFactory){
    
}])
Then use the methods by accessing the subproperties of the factory as though it was a copy of the returned object you declared earlier.

myApp.controller('myController', ['thisFactory', function(thisFactory){
    var someFood = thisFactory.food;
    var someDrink = thisFactory.drink;
    var someOfAll = thisFactory.getAll();
}])