angularjs dependency injection example

angularjs dependency injection example

Hello everyone,  I am going to share the example for how to work the angularjs dependency injection.  The example with detail explanations as given below, please follow  below steps.

Step 1 :  In The below example code, the factory and provider methods are run. That means the injector ($injector) are inject the dependencies.

Step 2 :  In The below example code, the AngularJs binds the controller to DOM.


AngularJs dependency injection code as given below.

var app = angular.module('appDI', []);

//factory method
app.factory('diFactory', function () {
    return {
        user: {
            name: 'Anil Singh'
        },
    };
});

//provider method
app.provider('diProvider', function () {
    this.$get = function (diFactory) {
        return {
            diFactory: diFactory
        };
    };
});

//controller method
app.controller('diCtrl', ['$scope', 'diProvider', function ($scope, diProvider) {
    $scope.name = diProvider.diFactory.user.name;
}]);

Live code sample with demo output

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>AngularJs Dependency Injection</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
    <script>
        var app = angular.module('appDI', []);

        //factory method
        app.factory('diFactory', function () {
            return {
                user: {
                    name: 'Anil Singh'
                },
            };
        });

        //provider method
        app.provider('diProvider', function () {
            this.$get = function (diFactory) {
                return {
                    diFactory: diFactory
                };
            };
        });

        //controller method
        app.controller('diCtrl', ['$scope', 'diProvider', function ($scope, diProvider) {
            $scope.name = diProvider.diFactory.user.name;
        }]);
    </script>
</head>
<body ng-app="appDI" ng-controller="diCtrl">
    <div>
        <div>
            <h1> Example for AngularJs Dependency Injection</h1>
        </div>
        <div>Result is = {{name}} </div>
    </div>
</body>
</html>




ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.