Aug 3, 2015

Dependency Injection In Angular Js



Dependency Injection (DI) is a software design pattern that allows you to remove hard coded dependencies between software components. It allows you to develop loosely coupled components by injecting dependencies either at compile time or run time.

AngularJS comes with a built-in dependency injection mechanism. Using Angular you can divide your apps into multiple components which can be inject into each other by using AngularJS dependency injection mechanism.
Methods to inject dependency in AngularJS

There are three ways to inject dependencies into your AngularJS components:

    The function parameter

    This is the easiest way to inject dependencies into your code. You have to just pass the dependencies as function parameters.

    In this method, Angular read the name of the passing parameters, and if those names are already registered as services, it will call your function when it’s invoked with those parameters.

        <script type="text/javascript">
        function MyController ($scope,$location) {
         $scope.name = 'dotnet-tricks.com';
         }
        </script>

    The $inject property
    The $inject property is an array of service names to inject. Hence defined your dependencies within $inject array. Also, the order of the values in the $inject array must match the order of the parameters to inject.

        <script type="text/javascript">
        var MyController = function(myscope, mylocation) {
         myscope.name='dotnet-tricks.com';
        }
        
        MyController['$inject'] = ['$scope', '$location'];
        </script>

    In the above code snippet, the $scope will be injected into myscope and $location into mylocation. Hence, parameters matching will be based on the order of values in the $inject array and it doesn’t matter what is the name of the parameters.
    The inline array

    You can also inject dependencies by using an inline array which will contain the dependencies.

        <script type="text/javascript">
        var MyController = ['$scope','$location',function MyController (scope, location) {
         scope.name = 'dotnet-tricks.com';
         }];
        
         //OR
         var app=angular.module('app',[]);
         app.controller('MyController',['$scope','$location',function MyController (scope, location) {
         scope.name = 'dotnet-tricks.com';
         }]);
         </script>

AngularJS has the following core types of objects and components which can be injected into each other using AngularJS dependency injection mechanism.

    Value

    Factory

    Service

    Provider

    Constant

No comments:

Post a Comment