{"id":3756,"date":"2014-02-22T08:42:48","date_gmt":"2014-02-22T03:12:48","guid":{"rendered":"http:\/\/JitendraZaa.com\/blog\/?p=3756"},"modified":"2014-04-08T10:22:42","modified_gmt":"2014-04-08T10:22:42","slug":"dependency-injection-in-angularjs","status":"publish","type":"post","link":"https:\/\/www.jitendrazaa.com\/blog\/webtech\/web\/dependency-injection-in-angularjs\/","title":{"rendered":"Dependency Injection in AngularJs"},"content":{"rendered":"<p style=\"text-align: justify;\">In this series, we have gone through many <a title=\"Basics of AngularJs\" href=\"https:\/\/jitendrazaa.com\/blog\/tag\/angularjs\/\">articles on AngularJs<\/a>. This time I will discuss about <a title=\"Dependency Injection in AngularJs\" href=\"http:\/\/docs.angularjs.org\/guide\/dev_guide.services.injecting_controllers\">Dependency Injection in AngularJs<\/a> .<\/p>\n<blockquote>\n<p style=\"text-align: justify;\">Dependency injection is a software design pattern that allows the removal of hard-coded dependencies and makes it possible to change them, whether at run-time or compile-time.<\/p>\n<\/blockquote>\n<p style=\"text-align: justify;\">Before going to DI first we have to know about Service.<\/p>\n<p><strong>What is Service , factory or Provider in AngularJs?<\/strong><\/p>\n<p style=\"text-align: justify;\">They all are same, with different way of writing. This (<em>Singleton design pattern<\/em>) defines dependency between your controller and View through application.<br \/>\nWe can Inject a service in Controller, which will watch over changes automatically and change its View as per required.<\/p>\n<p style=\"text-align: justify;\">We have many inbuilt standard service available like <a title=\"Scope in AngularJs\" href=\"http:\/\/docs.angularjs.org\/guide\/scope\">$scope<\/a>, <a title=\"$filter in AngularJs\" href=\"http:\/\/docs.angularjs.org\/api\/ng\/service\/$filter\">$filter<\/a>. All inbuilt services in AngularJS starts with this <strong>sign $<\/strong>. In same way we can create our own custom service and then inject in Controller.<!--more--><\/p>\n<p style=\"text-align: justify;\"><strong>Creating Custom Service :<\/strong><\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nvar myApp = angular.module('myApp', &#x5B;]);\r\n\r\nmyApp.service('filteredListService', function() {\r\n    this.retList = function(valLists){\r\n        return valLists;\r\n    }\r\n});\r\n<\/pre>\n<p>We can create Service by calling &#8220;<em>service<\/em>&#8220;\u009d method in module as shown above.<\/p>\n<p style=\"text-align: justify;\">I have created service by name &#8220;filteredListService&#8221;\u009d , which simply returns array passed to it. Advantage of doing this is that whenever list changes in our application after searching or sorting, I have to simply call this method of service and remaining job of updating UI and other stuff will be handled by framework. I don&#8217;t have to write any code, That&#8217;s awesome \ud83d\ude42<\/p>\n<p><strong>Passing Service in Controller:<\/strong><\/p>\n<p>Old definition of Controller was something like this in <a title=\"AngularJs Demo\" href=\"https:\/\/jitendrazaa.com\/blog\/tag\/angularjs\/\">previous articles<\/a> :<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nvar TableCtrl = myApp.controller('TableCtrl', function ($scope) {\r\n\/\/ ... code here\r\n});\r\n<\/pre>\n<p>New Definition of controller to pass service will be:<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nvar TableCtrl = myApp.controller('TableCtrl', function ($scope,filteredListService) {\r\n\/\/ ... code here\r\n});\r\n<\/pre>\n<p style=\"text-align: justify;\">As you can see, service name is passed as argument in controller. $scope is reserved keyword in AngularJs which represents Scope (link) between Controller and View.<\/p>\n<p><strong>Adding Service as DI<\/strong><\/p>\n<p>In order to inform AngularJs framework to add dependency between Service and our controller, we have to register it using below line of code :<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nTableCtrl.$inject = &#x5B;'$scope', 'filteredListService'];\r\n<\/pre>\n<p><strong>Difference between factory and Service?<\/strong><\/p>\n<p>If you define <em>factory<\/em> you will directly get value returned by method.<\/p>\n<p>If you define <em>Service<\/em>, you will get reference of methods. I normaly prefer Service because it gives me flexibility to define many methods in single service and very easy to maintain code.<\/p>\n<p>From Documentation:<\/p>\n<p><strong>Services<\/strong><br \/>\n<em>Syntax: module.service( &#8216;serviceName&#8217;, function );<\/em><\/p>\n<p>Result: When declaring serviceName as an injectable argument you will be provided with <em><span style=\"text-decoration: underline;\">an instance of the function<\/span><\/em>. In other words new FunctionYouPassedToService().<\/p>\n<p><strong>Example :<\/strong><\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nvar app = angular.module('myApp', &#x5B;]);\r\n\r\n\/\/ Service definition\r\napp.service('testService', function(){\r\n    this.sayHello= function(text){\r\n        return &quot;Service says \\&quot;Hello &quot; + text + &quot;\\&quot;&quot;;\r\n    };\r\n});\r\n\r\n\/\/ AngularJS Controller that uses the service\r\nfunction HelloCtrl($scope, testService)\r\n{\r\n    $scope.fromService = testService.sayHello(&quot;World&quot;);\r\n}\r\n<\/pre>\n<p><strong>Factories<\/strong><br \/>\n<em>Syntax: module.factory( &#8216;factoryName&#8217;, function ); <\/em><\/p>\n<p>Result: When declaring factoryName as an injectable argument you will be <em><span style=\"text-decoration: underline;\">provided with the value<\/span><\/em> that is returned by invoking the function reference passed to module.factory.<\/p>\n<p><strong>Example :<\/strong><\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nvar app = angular.module('myApp', &#x5B;]);\r\n\r\n\/\/ Factory\r\napp.factory('testFactory', function(){\r\n    return {\r\n        sayHello: function(text){\r\n            return &quot;Factory says \\&quot;Hello &quot; + text + &quot;\\&quot;&quot;;\r\n        }\r\n    }\r\n});\r\n\r\n\/\/ AngularJS Controller that uses the factory\r\nfunction HelloCtrl($scope, testFactory)\r\n{\r\n    $scope.fromFactory = testFactory.sayHello(&quot;World&quot;);\r\n}\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>In this series, we have gone through many articles on AngularJs. This time I will discuss about Dependency Injection in AngularJs . Dependency injection is a software design pattern that allows the removal of hard-coded dependencies and makes it possible to change them, whether at run-time or compile-time. Before going to DI first we have [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"jz_research_post":"","_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_post_was_ever_published":false},"categories":[26],"tags":[35,74,178],"class_list":["post-3756","post","type-post","status-publish","format-standard","hentry","category-web","tag-angularjs","tag-dependency-injection","tag-service"],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack-related-posts":[{"id":3751,"url":"https:\/\/www.jitendrazaa.com\/blog\/webtech\/web\/pagination-and-sorting-of-data-table-using-angularjs\/","url_meta":{"origin":3756,"position":0},"title":"Pagination, Searching and Sorting of Data Table  using AngularJS","author":"Jitendra Zaa","date":"February 22, 2014","format":false,"excerpt":"We have already discussed \"Basics of AngularJS\" and \"Simple Searching and Sorting\". In this article, we will add Pagination feature also to our previous example. What makes difficult is Sorting result when values are returned from Search and pagination is enabled. Unlike previous post we cannot use standard \"OrderBy\" filter\u2026","rel":"","context":"In &quot;HTML&quot;","block_context":{"text":"HTML","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/webtech\/web\/"},"img":{"alt_text":"Searching Sorting and Pagination in Table using AngularJS","src":"https:\/\/i0.wp.com\/jitendrazaa.com\/blog\/wp-content\/uploads\/2014\/02\/Searching-Sorting-and-Pagination-in-Table-using-AngularJS-300x156.png?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]},{"id":3675,"url":"https:\/\/www.jitendrazaa.com\/blog\/webtech\/web\/getting-started-with-angularjs\/","url_meta":{"origin":3756,"position":1},"title":"Getting Started with AngularJs","author":"Jitendra","date":"February 15, 2014","format":false,"excerpt":"AngularJs is most accepted MVC framework in Javascript developed by Google. In my point of view, If its developed by Google then there must be something new and unique about this library. It can be used to provide MVC architect to your web application. It has great developers community, so\u2026","rel":"","context":"In &quot;HTML&quot;","block_context":{"text":"HTML","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/webtech\/web\/"},"img":{"alt_text":"AngularJS by Google","src":"https:\/\/i0.wp.com\/jitendrazaa.com\/blog\/wp-content\/uploads\/2014\/02\/AngularJS-by-Google-300x84.png?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]},{"id":3745,"url":"https:\/\/www.jitendrazaa.com\/blog\/webtech\/web\/table-with-sorting-and-searching-using-angularjs\/","url_meta":{"origin":3756,"position":2},"title":"Table with Sorting and Searching using AngularJS","author":"Jitendra","date":"February 22, 2014","format":false,"excerpt":"I hope, from last article you got basic information about AngularJS. This time, I will demonstrate how to add basic Searching and Sorting capability to data table using AngularJs. Output will look something like this : Prerequisite Libraries : UnderscoreJs Bootstrap CSS AngularJs Complete Html Code : [html] <div ng-app=\"myApp\">\u2026","rel":"","context":"In &quot;HTML&quot;","block_context":{"text":"HTML","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/webtech\/web\/"},"img":{"alt_text":"Searching and Sorting in Table using AngularJS","src":"https:\/\/i0.wp.com\/jitendrazaa.com\/blog\/wp-content\/uploads\/2014\/02\/Searching-and-Sorting-in-Table-using-AngularJS-300x128.png?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]},{"id":3917,"url":"https:\/\/www.jitendrazaa.com\/blog\/salesforce\/ajax-based-autocomplete-typeahead-directive-in-angularjs\/","url_meta":{"origin":3756,"position":3},"title":"Ajax based AutoComplete \/ TypeAhead Directive in AngularJS","author":"Jitendra","date":"July 15, 2014","format":false,"excerpt":"Previously we already discussed below Auto Complete components: Ajax Based Multiselect JQuery Autocomplete Control in ASP.Net AutoComplete Component in Visualforce using JQueryUI In this article, we will be creating TypeAhead Directive (Auto Complete) again in Salesforce However this time we will use AngularJs. Why we are using AngularJS ? We\u2026","rel":"","context":"In &quot;Salesforce&quot;","block_context":{"text":"Salesforce","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/salesforce\/"},"img":{"alt_text":"TypeAhead Demo using AngularJs","src":"https:\/\/i0.wp.com\/www.jitendrazaa.com\/blog\/wp-content\/uploads\/2014\/07\/TypeAhead-Demo-using-AngularJs.png?resize=350%2C200&ssl=1","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/www.jitendrazaa.com\/blog\/wp-content\/uploads\/2014\/07\/TypeAhead-Demo-using-AngularJs.png?resize=350%2C200&ssl=1 1x, https:\/\/i0.wp.com\/www.jitendrazaa.com\/blog\/wp-content\/uploads\/2014\/07\/TypeAhead-Demo-using-AngularJs.png?resize=525%2C300&ssl=1 1.5x, https:\/\/i0.wp.com\/www.jitendrazaa.com\/blog\/wp-content\/uploads\/2014\/07\/TypeAhead-Demo-using-AngularJs.png?resize=700%2C400&ssl=1 2x"},"classes":[]},{"id":3951,"url":"https:\/\/www.jitendrazaa.com\/blog\/salesforce\/creating-salesforce-query-builder-in-node-js-and-angularjs-using-salesforce-rest-api-and-oauth2\/","url_meta":{"origin":3756,"position":4},"title":"Creating Salesforce Query Builder in Node.js and AngularJs using Salesforce REST API and OAuth2 with Heroku Button","author":"Jitendra","date":"August 18, 2014","format":false,"excerpt":"In this post, we will be creating a\u00a0Salesforce Query (SOQL) Builder.\u00a0It uses Google's Angularjs MVC Javascript library and REST API provided by Salesforce. For Authentication, it uses OAuth2. Node.js is used as a primary language and hosted on Heroku. If you want to directly deploy to your Heroku Account, You\u2026","rel":"","context":"In &quot;HTML&quot;","block_context":{"text":"HTML","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/webtech\/web\/"},"img":{"alt_text":"SOQL Builder Using Node.js AngularJs Salesforce REST API on Heroku","src":"https:\/\/i0.wp.com\/www.jitendrazaa.com\/blog\/wp-content\/uploads\/2014\/08\/SOQL-Builder-Using-Node.js-AngularJs-Salesforce-REST-API-on-Heroku-1024x504.png?resize=350%2C200&ssl=1","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/www.jitendrazaa.com\/blog\/wp-content\/uploads\/2014\/08\/SOQL-Builder-Using-Node.js-AngularJs-Salesforce-REST-API-on-Heroku-1024x504.png?resize=350%2C200&ssl=1 1x, https:\/\/i0.wp.com\/www.jitendrazaa.com\/blog\/wp-content\/uploads\/2014\/08\/SOQL-Builder-Using-Node.js-AngularJs-Salesforce-REST-API-on-Heroku-1024x504.png?resize=525%2C300&ssl=1 1.5x"},"classes":[]},{"id":4384,"url":"https:\/\/www.jitendrazaa.com\/blog\/webtech\/getting-started-with-react\/","url_meta":{"origin":3756,"position":5},"title":"Getting started with React","author":"Jitendra","date":"April 15, 2015","format":false,"excerpt":"React is open source Javascript library used by Facebook and currently very popular amongst web developers to create user interface. React can be used as View part of MVC design pattern with powerful templating feature supported by \"JavaScript syntax extension (JSX)\". React focuses on component based development where each components\u2026","rel":"","context":"In &quot;Web Technology&quot;","block_context":{"text":"Web Technology","link":"https:\/\/www.jitendrazaa.com\/blog\/category\/webtech\/"},"img":{"alt_text":"React Javascript library by Facebook","src":"https:\/\/i0.wp.com\/www.jitendrazaa.com\/blog\/wp-content\/uploads\/2015\/04\/fbreact.png?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]}],"jetpack_likes_enabled":true,"_links":{"self":[{"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/posts\/3756","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/comments?post=3756"}],"version-history":[{"count":3,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/posts\/3756\/revisions"}],"predecessor-version":[{"id":3810,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/posts\/3756\/revisions\/3810"}],"wp:attachment":[{"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/media?parent=3756"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/categories?post=3756"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.jitendrazaa.com\/blog\/wp-json\/wp\/v2\/tags?post=3756"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}