fastread homefastrread library fastread menu

AngularJS : Injecting a Value

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

❰ Previous Next ❱

AngularJS comes with a built-in dependency injection mechanism. You can divide your application into multiple different types of components which AngularJS can inject into each other. Modularizing your application makes it easier to reuse, configure and test the components in your application.

AngularJS contains the following core types of objects and components:

  • Value
  • Factory
  • Service
  • Provider
  • Constant

These core types can be injected into each other using AngularJS dependency injection mechanism. Throughout the rest of this text I will explain how to define and inject these components into each other.



A value in AngularJS is a simple object. It can be a number, string or JavaScript object. Values are typically used as configuration which is injected into factories, services or controllers.

A value has to belong to an AngularJS module. Here are three examples that add values to an AngularJS module:

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

myModule.value("numberValue", 999);

myModule.value("stringValue", "abc");

myModule.value("objectValue", { val1 : 123, val2 : "abc"} );

The values are defined using the value() function on the module. The first parameter is the name of the value, and the second parameter is the value itself. Factories, services and controllers can now reference these values by their name.

Injecting a Value

Injecting a value into an AngularJS controller function is done simply by adding a parameter with the same name as the value (the first parameter passed to the value() function when the value is defined). Here is an example:

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

myModule.value("numberValue", 999);

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



Notice how the second parameter of the controller function has the same name as the value.

❰ Previous Next ❱