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

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Buy Books Online at Best Prices

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.