Hi Friend if you are fresher read my previous post of angular Js tutorial.
Hi friends today you study injector,
inject & Dependency Injection.
Injector: - Gets the injector for the current element or its parent.
This allows you to ask for dependencies defined for the modules in these
elements.
Ex: - app.controller("MyCtrl",
function ($scope, $injector) {
$scope.doSomething
= function () {
var
s1 = $injector.get('s1')
Inject: - Resolves dependencies and injects them into a function.
Ex: - fnctrl3["$inject"]
= ["$scope", "$rootScope"];
app.controller("ctrl3",
fnctrl3);
Dependency
Injection: - Dependency injection (DI) is a design pattern where dependencies
are defined in an application as part of the configuration. AngularJS uses
dependency injection to load module dependencies when an application first
starts. Dependency injection also helps to make an application more testable.
That is one of the main advantages of using AngularJS to build JavaScript
applications. AngularJS applications are much easier to test than applications
written with most JavaScript frameworks.To
facilitate this configuration, AngularJS provides three ways to declare
dependencies
Directly
using the parameters of a function, as we can see in the following example:
•function User Controller ($scope, $http, $resource, $ownservice) {
Var
user;
$scope.
User = {
name:
"Shiva",
age:
"27"
}
}
• Using an array, as shown here:-
User. Controller('User Controller', ['$scope','$http' function ($scope, $http)
{...}]);
• Using the $inject property, as follows:-
User
Controller var = function ($scope, $http)
{...};
User
Controller $ inject = ['$scope','$http'];
user.Module.controller
('User Controller' User Controller);
Angular
Js use dependency with several types
- Value
- Factory
- Service
- Provider
- Constant
These all you learn in my previous video part 7
1. Now create a demo projects:-
2. Open your visual studio
3. Create new folder on desktop
4. Open that folder on visual studio & add
html file name with Dependency.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>AngularJS Dependency Injection</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var app = angular.module("app", []);
app.controller("ctrl1", function ($scope,
$rootScope) {
$scope.Name = "Shiva";
});
app.controller("ctrl2", ["$scope", "$rootScope", function (s, r) {
s.Name = "Kshma";
}]);
var fnctrl3 = function (scope, rootscope) {
scope.Name = "Ashita";
};
fnctrl3["$inject"] = ["$scope", "$rootScope"];
app.controller("ctrl3",
fnctrl3);
</script>
</head>
<body ng-app="app">
<div ng-controller="ctrl1">
{{Name}}
</div>
<div ng-controller="ctrl2">
{{Name}}
</div>
<div ng-controller="ctrl3">
{{Name}}
</div>
</body>
</html>
Output:-
Hope
you all understand about inject, injector & dependency injection.
No comments:
Post a Comment