In the previous section on providers, configuration of a provider through the
module.config()
function is seen. Unfortunately, values cannot be injected into the
module.config()
function but the constants can be injected. AngularJS constants are defined with the help of
module.constants()
function.
index.html
[html]
<html>
<head>
<title>AngularJS Dependency Injection</title>
</head>
<body>
<h2>AngularJS Dependency Injection</h2>
<div ng-app="spApp" ng-controller="SPController">
<p>Enter a number: <input type="number" ng-model="number" />
<button ng-click="square()">X<sup>2</sup></button>
<p>Result: {{result}}</p>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="App.js"></script>
<script src="provider.js"></script>
<script src="value.js"></script>
<script src="factory.js"></script>
<script src="service.js"></script>
<script src="Controller.js"></script>
</body>
</html>
[/html]
App.js
[javascript]
var mainApp = angular.module("spApp", []);
[/javascript]
Controller.js
[javascript]
mainApp.controller('SPController', function($scope, CalcService, defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});
[/javascript]
factory.js
[javascript]
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
}
return factory;
});
[/javascript]
provider.js
[javascript]
mainApp.config(function($provide) {
$provide.provider('MathService', function() {
this.$get = function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
}
return factory;
};
});
});
[/javascript]
service.js
[javascript]
var mainApp = angular.module("spApp", []);
[/javascript]
value.js
[javascript]
mainApp.value("defaultInput", 5);
[/javascript]
Output: