How to Inject a Service, Provider by factory?

In the below example, I am going to share the how to Inject the service and provider by factory method. Please see the below detail as given.

<html>
<head>
    <title> AngularJs Dependency Injection for Service, and Provider</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    <script>
        var app = angular.module("diApp", []);

        app.config(function ($provide) {
            $provide.provider('diFactory', function () {
                this.$get = function () {
                    var factory = {};

                    factory.multiply = function (i, j) {
                        return i * j;
                    }
                    return factory;
                };
            });
        });


        app.factory('diFactory', function () {
            var factory = {};

            factory.multiply = function (i, j) {
                return i * j;
            }
            return factory;
        });

        app.service('diService', function (diFactory) {
            this.square = function (i) {
                return diFactory.multiply(i, i);
            }
        });

        app.controller('diCtrl', ['$scope', 'diService', function ($scope, diService) {
            $scope.number = 6;
            $scope.result = diService.square($scope.number);
        }]);
    </script>
</head>
<body>
    <h2>AngularJS Dependency Injection</h2>
    <div ng-app="diApp" ng-controller="diCtrl">
        <button>6<sup>2</sup> OR (6*6)</button>
        <p>Result: {{result}}</p>
    </div>
</body>
</html>

About Blogger

ANIL SINGH

Hey! I am Anil Singh. I am Active Blogger, Writer and Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
http://www.code-sample.com
http://www.code-sample.xyz

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment

SQL Server NodeJs TypeScript JavaScript Angular SQL Server My Book