{"id":609,"date":"2016-02-28T04:01:00","date_gmt":"2016-02-28T04:01:00","guid":{"rendered":"https:\/\/staging.infragistics.com\/blogs\/?p=609"},"modified":"2025-02-25T14:28:16","modified_gmt":"2025-02-25T14:28:16","slug":"injecting-dependency-in-angularjs","status":"publish","type":"post","link":"https:\/\/www.infragistics.com\/blogs\/injecting-dependency-in-angularjs","title":{"rendered":"Injecting Dependency in AngularJS Apps"},"content":{"rendered":"\n<p>When you start learning the very first characteristics of AngularJS, you may come across something called Dependency Injection (DI): the premise that AngularJS injects dependencies whenever an application needs them. As a developer, our task is only to pass the dependency to the module and everything else will be taken care by AngularJS. Now I can show you how it&#8217;s all done in an easy way using one of the best <a href=\"\/products\/ignite-ui-angular\">Angular Component Libraries<\/a> on the market &#8211; Ignite UI for Angular.<\/p>\n\n\n\n<p>To create a controller, we pass $scope object and other dependencies to the module\u2019s controller function. For example, to create a ProductController, we are passing $scope object and Calculator service dependencies. This reiterates the knowledge that, as a developer, our job is to pass the dependencies and AngularJS will inject them whenever the application needs them.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.dependecyinjection\/2335.pic1.png\" alt=\"  create a controller, we pass $scope object and other dependencies to the module\u2019s controller function\" title=\" create a controller, we pass $scope object and other dependencies to the module\u2019s controller function\"\/><\/figure>\n\n\n\n<p>From our standpoint, we really don\u2019t care about <i>how<\/i> AngularJS injects dependencies \u2013 we don\u2019t need to know how the injection process works to develop applications. It is, however, better if we know a variety of ways for passing dependencies. In AngularJS, dependencies can be passed in three possible ways. They are as follows:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Passing a dependency as Function Arguments<\/li>\n\n\n\n<li>Passing a dependency as Array Arguments<\/li>\n\n\n\n<li>Passing a dependency using the $inject service<\/li>\n<\/ol>\n\n\n\n<p>Let us explore these options one by one.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"passing-a-dependency-as-a-function-argument\">Passing a dependency as a Function Argument <\/h2>\n\n\n\n<p>Perhaps you find yourself frequently passing a dependency as a function argument, which is perfectly fine. For example, we pass a $scope object to create a controller as shown in the listing below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">app.controller(\"ProductController\", function ($scope) {\n    $scope.message = \"Hey I am passed as function argument\"\n});<\/pre>\n\n\n\n<p>Passing dependencies as function arguments works well until we deploy the application in the production with a minified version of the application. Usually, to improve the performance, we minify the application in production, but passing the dependency as a function argument breaks when we minify the application.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.dependecyinjection\/8877.pic2.PNG\" alt=\" Passing dependencies as function arguments works well until we deploy the application\" title=\"Passing dependencies as function arguments works well until we deploy the application\"\/><\/figure>\n\n\n\n<p>Obviously in production, for better performance, we would like to deploy the minified version of the application, but the application will break because the parameter name will change to a shorter alias name. To avoid this break in production, we should choose another option.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"passing-a-dependency-as-array-arguments\">Passing a dependency as Array Arguments <\/h2>\n\n\n\n<p>Possibly the most popular way of passing a dependency in an AngularJS application is passing them as Array Arguments. When we pass a dependency as an Array Argument, the application does not break in production when we minify the application. We can do this in two possible ways:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Using the Named function<\/li>\n\n\n\n<li>Using the Inline Anonymous function<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"using-the-named-function\">Using the Named function <\/h2>\n\n\n\n<p>We can pass dependencies as Array Arguments with the named function as shown in the listing below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">var app = angular.module('app', []);\n\nfunction ProductController($scope) {\n    $scope.greet = \"Infragistics\";\n};\napp.controller('ProductController', ['$scope', ProductController]);<\/pre>\n\n\n\n<p>As you\u2019ll notice, we are passing a dependency $scope object in the array along with the name of the controller function. More than one dependency can be passed, as long as they are separated by a comma. For example, we can pass both $http service and the $scope object as dependencies as shown in the listing below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">var app = angular.module('app', []);\n\nfunction ProductController($scope,$http) {\n    $scope.greet = $http.get(\"api.com\");       \n};\napp.controller('ProductController', ['$scope','$http', ProductController]);<\/pre>\n\n\n\n<p>As we discussed earlier, passing dependencies as Array Arguments does not break application when we minify the application.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"using-the-inline-anonymous-function\">Using the Inline Anonymous function <\/h2>\n\n\n\n<p>Personally, I find using a named function much more convenient than using an inline anonymous function. For me, it\u2019s easy to manage the named controller function. If you prefer the inline function, you can pass dependencies as array arguments exactly the same way you pass them in named controller functions. We can pass dependencies in an inline function as array arguments, as shown in the listing below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">var app = angular.module('app', []);\n\napp.controller('ProductController', ['$scope', '$http', function ($scope,$http) {\n    $scope.greet = \"Foo is Great!\"\n}]);<\/pre>\n\n\n\n<p>Keep in mind that dependencies injected as Array arguments work even if we minify the application.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.dependecyinjection\/8322.pic3.PNG\" alt=\" Keep in mind that dependencies injected as Array arguments work even if we minify the application\" title=\"Keep in mind that dependencies injected as Array arguments work even if we minify the application\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"passing-a-dependency-using-the-inject-service\">Passing a dependency using the $inject service<\/h2>\n\n\n\n<p>There is one more way to inject dependencies in AngularJS: by using the $inject service. In doing so, we manually inject the dependencies. We can inject $scope object dependencies using the $inject service as shown in the listing below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">function ProductController($scope){\n    $scope.greet = \"Foo is Not Great!5\";\n}\n\nProductController.$inject = ['$scope'];\n\napp.controller('ProductController', ProductController);<\/pre>\n\n\n\n<p>Using the $inject service also does not break the application when we minify the application for production. Most often we will find $inject services being used to inject dependencies in unit testing of the controller.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.dependecyinjection\/8053.pic4.PNG\" alt=\" Using the $inject service also does not break the application when we minify the application for production.\" title=\"Using the $inject service also does not break the application when we minify the application for production.\"\/><\/figure>\n\n\n\n<p>Before we end this article, let us see how we can use $inject to inject a service to the controller in a real-time application. We have created a service as shown in the listing below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">app.factory(\"Calculator\", function () {\n    return {\n        add: function (a, b) {\n            return a + b;\n        }\n    }\n});<\/pre>\n\n\n\n<p>We need to use a Calculator service inside CalController. The CalController can be created as shown in the listing below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">app.controller('CalController', CalController);\nfunction CalController($scope, Calculator) {\n\n    $scope.result = 0;\n    $scope.add = function () {\n        alert(\"hi22\");\n        $scope.result= Calculator.add($scope.num1, $scope.num2);\n    }\n};<\/pre>\n\n\n\n<p>At this point, the application should work because dependencies are passed as function arguments. However, the application will break when we minify it. So let us go ahead and inject the dependencies using the $inject as shown in the listing below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">CalController.$inject = ['$scope', 'Calculator'];<\/pre>\n\n\n\n<p>On the view, the controller can be&nbsp;used as shown below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;div ng-controller=\"CalController\">\n    &lt;input type=\"number\" ng-model=\"num1\" placeholder=\"Enter number 1\" \/>\n    &lt;input type=\"number\" ng-model=\"num2\" placeholder=\"Enter number 2\" \/>\n    &lt;button ng-click=\"add()\">Add&lt;\/button>\n    {{result}}\n&lt;\/div><\/pre>\n\n\n\n<p>And there you have it &#8211; the easiest way to interject dependencies in AngularJS apps.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><a href=\"\/products\/ignite-ui-angular\/download\"><img decoding=\"async\" src=\"https:\/\/static.infragistics.com\/marketing\/Blog-in-content-ads\/Ignite-UI-Angular\/ignite-ui-angular-you-get-ad.gif\" alt=\"Ignite UI for Angular library\"\/><\/a><\/figure>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>A brief overview on passing dependencies in AngularJS using the function argument, array arguments, and the $inject service.<\/p>\n","protected":false},"author":65,"featured_media":2368,"comment_status":"publish","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7],"tags":[],"class_list":["post-609","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-angular"],"_links":{"self":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts\/609","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/users\/65"}],"replies":[{"embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/comments?post=609"}],"version-history":[{"count":2,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts\/609\/revisions"}],"predecessor-version":[{"id":1952,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts\/609\/revisions\/1952"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/media\/2368"}],"wp:attachment":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/media?parent=609"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/categories?post=609"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/tags?post=609"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}