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.
Demo link click on http://embed.plnkr.co/Snv9zO/preview
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" />
<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>
OutPut : go to link http://embed.plnkr.co/Snv9zO/preview