AngularJS Dependency Injection ApplicationEnter a number: Result: {{result}}
<!-- AngularJS provides a supreme Dependency Injection mechanism. It provides following core components which can be injected into each other as dependencies.
value
factory
service
provider
constant-->
<html> <head> <title>AngularJS Dependency Injection</title> </head> <body> <h2>AngularJS Dependency Injection Application</h2> <div ng-app = "mainApp" ng-controller = "CalcController"> <p>Enter a number: <input type = "number" ng-model = "number" /></p> <button ng-click = "square()">X<sup>2</sup></button> <p>Result: {{result}}</p> </div> <script> var mainApp = angular.module("mainApp", []); //value mainApp.config(function($provide) { $provide.provider('MathService', function() { this.$get = function() { var factory = {}; factory.multiply = function(a, b) { return a * b; } return factory; }; }); }); mainApp.value("defaultInput", 5); //factory mainApp.factory('MathService', function() { var factory = {}; factory.multiply = function(a, b) { return a * b; } return factory; }); //services mainApp.service('CalcService', function(MathService){ this.square = function(a) { return MathService.multiply(a,a); } }); //provider mainApp.controller('CalcController', function($scope, CalcService, defaultInput) { $scope.number = defaultInput; $scope.result = CalcService.square($scope.number); $scope.square = function() { $scope.result = CalcService.square($scope.number); } }); </script> </body> </html> |