fastread homefastrread library fastread menu

AngularJS : Injecting Values Into a Factory

Tutorial by:Sumit Chauhan      Date: 2016-08-12 00:36:59

❰ Previous Next ❱


Factory is a function that creates values. When a service, controller etc. needs a value injected from a factory, the factory creates the value on demand. Once created, the value is reused for all services, controllers etc. which need it injected. Thus, a factory differs from a value in that it can use a factory function to create the object it returns. You can also inject values into a factory for use when creating the object. You cannot do that with a value.

Here is an example that defines a factory on a module, and a controller which gets the factory created value injected:

var myModule = angular.module("myModule", []);

myModule.factory("myFactory", function() {
    return "a value";

myModule.controller("MyController", function($scope, myFactory) {



As you can see, it is very similar to defining and injecting a value object. Keep in mind that it is not the factory function that is injected, but the value produced by the factory function.

Injecting Values Into a Factory

You can inject a value into a factory. It works just like when a value is injected into a controller. Here is an example:

var myModule = angular.module("myModule", []);

myModule.value("numberValue", 999);

myModule.factory("myFactory", function(numberValue) {
    return "a value: " + numberValue;

In this example the injected value is used to create the object created by the factory function.

❰ Previous Next ❱