SharePoint Pals
 | Sign In
How Dependency Injection works in Angular JS
by Tarun Kumar Chatterjee 5 Dec 2015
Author
.Net – Technology Specialist
Visits   
Today  :   2     Total  :    4511

“Factory” and “Service” are nothing but different ways of doing DI (Dependency injection) in angular JS.

When we define DI using a “factory” it does not create an instance. It just passes the method and later consumer internally has to make calls to the factory for object instances. So, if we want to create different types of objects depending on scenarios we can use “factory”.

Whereas if we have utility or shared functions to be injected like Utility, Logger, Error handler etc. can go for “service”. So, in that case Global and Shared instance can be created.

Let see the actual implementation of “factory”:

First let me create an Employee controller class and which will have a method below:

 public ActionResult Employee()
         {
             return View();
         }  
 

In next step we need to create angular JS EmployeeController and the other methods associated with it. Here are the codes:

 var app = angular.module("AppModule",[]); // Load App Module
 app.controller("EmployeeController", EmployeeController); // Registering controller  
 
 

We need to tell Angular that the “CreateEmployee” method needs to be passed in the input. For that we need to call the “factory” method and map the “CreateEmployee” method with the input parameter “objFactory” for dependency injection.

 app.factory("objFactory", CreateEmployee); // Create factory

Below is a simple “EmployeeController” which takes “objFactory” as the input. Depending on the EmployeeType “factory” object it will create Email and Department and will assign the result to $scope.Employee

 function EmployeeController($scope, objFactory)
 {
 
     $scope.Employee = {};
     $scope.Init = function (TypeofEmployee) {
 
         if (TypeofEmployee == "1") {
             $scope.Employee = objFactory.CreateWithDepartment();
         }
         if (TypeofEmployee == "2") {
             $scope.Employee = objFactory.CreateWithEmail();
         }
         if (TypeofEmployee == "3") {
             $scope.Employee = objFactory.CreateWithEmailDepartment();
         }
     }
 }
 

In the below factory method “CreateEmployee“ we can see we have three functions:-

· “CreateWithDepartment” which creates “Employee” with “Department” objects inside it.

· “CreateWithEmail” which creates “Employee” object with “Email” objects inside it.

· “CreateWithEmailDepartment” which creates “Employee” object with “Email” and “Department” objects.

 function CreateEmployee() {
 
     return {
 
         CreateWithDepartment: function () {
             var emp = new Employee();
             emp.Department = CreateDepartment();
             return emp;
         },
         CreateWithEmail: function () {
             var emp = new Employee();
             emp.Email = {};
             emp.Email = CreateEmail();
             return emp;
         },
         CreateWithEmailDepartment: function () {
             
             var emp = new Employee();
             emp.Email = CreateEmail();
             emp.Department = CreateDepartment();
             return emp;
         }
     }
 }
 

Here the other pertinent methods are being used by “CreateEmployee”

 function Employee() {
     this.EmployeeCode = "0001";
     this.EmployeeName = "Tarun Kumar Chatterjee";
 }
 function Email() {
     this.EmailID = "tarun@abc.com";
 }
 function Department() {
     this.Department1 = "Test Department 1";
     this.Department2 = "Test Department 2";
 }
 function CreateDepartment()
 {
     var dept = new Department();
     return dept;
 }
 function CreateEmail()
 {
     var email =  new Email();
     return email;
 }
 

Now, let me create an Employee view with the following code:

 @{
     ViewBag.Title = "Employee";
     Layout = "~/Views/Shared/_Layout.cshtml";
 }
 
 <h2>Factory</h2>
 
 <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
 <body>
 
 
     <div ng-app="AppModule">
 
         <div ng-controller="EmployeeController" ng-init="Init(1)">
 
             <table cellpadding="1" cellspacing="1" width="100%" style="background-color:none; border:solid 1px black;">
                 <tr>
                     <td width="50%">
                         <div>
                             {{Employee.EmployeeName}}
                         </div>
                     </td>
                     <td width="50%">
                         <div>
                             {{Employee.Department.Department1}}
                         </div>
                     </td>
                 </tr>
             </table>
         </div>
         <br />
         <div ng-controller="EmployeeController" ng-init="Init(2)">
             <table cellpadding="1" cellspacing="1" width="100%" style="background-color:none; border:solid 1px black;">
                 <tr>
                     <td width="50%">
                         <div>
                             {{Employee.EmployeeName}}
                         </div>
                     </td>
                     <td width="50%">
                         <div>
                             {{Employee.Email.EmailID}}
                         </div>
                     </td>
                 </tr>
             </table>
         </div>
         <br />
         <div ng-controller="EmployeeController" ng-init="Init(3)">
             <table cellpadding="1" cellspacing="1" width="100%" style="background-color:none; border:solid 1px black;">
                 <tr>
                     <td width="50%">
                         <div>
                             {{Employee.EmployeeName}}
                         </div>
                     </td>
                     <td width="50%">
                         <div>
                             {{Employee.Department.Department2}}
                         </div>
                     </td>
                 </tr>
             </table>
         </div>
     </div>
 </body>
 

Build the solution and run. The output will be looking like:

clip_image002

Now let see the actual implementation of “service”:

First I have created an EmployeeService controller class and which will have a method below:

 public ActionResult EmployeeService()
         {
             return View();
         }
 

Again in next step we need to create angular JS EmployeeServiceController and the other methods associated with it. Here are the codes:

 var app = angular.module("AppModule",[]); // Load App Module
 
 app.controller("EmployeeServiceController", EmployeeServiceController); // Registering Controller
 

Below code to inject “HitCounter” class instance in the “EmployeeServiceController”

 app.service("HitCounter", HitCounter); // Injects the object
 
 function EmployeeServiceController($scope, HitCounter) {
     $scope.HitCounter = HitCounter;
 }
 

Below is a simple “HitCounter” class which has a “Hit” function and this function increments the variable count internally every time you call hit the button.

 function HitCounter() {
     var i = 0;
     this.Hit = function () {
         i++;
         alert(i);
     };
 }
 

Now add a view named as “EmployeeService.chtml” with the following code

 @{
     ViewBag.Title = "EmployeeService";
     Layout = "~/Views/Shared/_Layout.cshtml";
 }
 
 <h2>Service</h2>
 
 <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
 <body>
 
 
     <div ng-app="AppModule">
 
         <div ng-controller="EmployeeServiceController" ng-init="Init(1)">
             <input type="button" ng-click="HitCounter.Hit()" value="test1">           
         </div>
         <br/>
         <div ng-controller="EmployeeServiceController">
             <input type="button" ng-click="HitCounter.Hit()" value="test2">
         </div>
         
     </div>
 
 
 </body>
 

If we execute the above code we will see counter values getting incremented even if we are in different controller instances.

Here are the outputs:

Click on test1 button

clip_image004

Click on test2 button

clip_image006

Hope it will help to have some basic idea about Angular “factory” & “service”.

Happy Coding

Tarun Kumar Chatterjee

blog comments powered by Disqus

SharePoint Pals

Pals
SharePoint Pals, a community portal for SharePoint developers, Administrators and End Users. Let's join hands and share the point together.
Read this on mobile

Training

Angular Js Training In Chennai
Advanced Angular Js training with real world developer scenarios
Angular Js, Web Api and Ionic for .Net Developers
All in one client side application development for .Net developers
Angular Js For SharePoint Developers
Get ready for the future. Its no more just C#

Get Connected

SharePoint Resources

SharePoint 2013 and 2010 Web Parts
Free Web Parts with Source Code for SharePoint Community




SharePoint 2013 Books and Tutorials
Collection of free SharePoint 2013 books and tutorials (eBooks, pdfs)

Supported By

Contribute your article and be eligible for a one month Free Subscription for Plural Sight. The Author of the most popular New Article (published in the previous month) will be awarded with a Free One month Plural Sight Subscription. Article can be sent to articles@sharepointpals.com in a word document.

Related Resources

Recent Tweets

Twitter January 15, 00:25
How To Enable Target Value And Actual Value In #D3 Gauge Chart https://t.co/VxSi4QnNrC

Twitter January 15, 00:24
How To Open #SharePoint List Hyperlink Column In Modal #Popup Window https://t.co/EQ7HkoZDkX

Twitter January 15, 00:24
Quick Introduction To #Asp.NetCore And It’s Features https://t.co/zAXObHCFpH

Twitter January 15, 00:22
How To Configure #PerformancePoint Services To Use Secure Store In #SharePoint 2013 https://t.co/LEwnUoI7EY

Twitter January 15, 00:21
How To Block Or Disable #Office365 Services https://t.co/Yvp2VPFIRP

Follow us @SharePointPals
Note: For Customization and Configuration, CheckOutRecent Tweets Documentation