In AngularJS Dependency Injection
is achieved by injecting objects to the controller, in normal implementations
we use the $scope object in the
controller to set values and pass it to the view for display.
In the following example we shall create a service and inject the service to the controller, this way all the data used in the controller are fed from the service, the service can be changes or pass different service objects to test the controller and the view.
HTML ViewIn the following example we shall create a service and inject the service to the controller, this way all the data used in the controller are fed from the service, the service can be changes or pass different service objects to test the controller and the view.
<html ng-app="DIApp">
<head>
<meta charset="utf-8">
<title>AngularJS - Basic</title>
</head>
<body>
<div
ng-controller="DIController">
First
Name: <input type="text" ng-model="firstName"><br>
Last
Name: <input type="text" ng-model="lastName"><br>
</div>
<script src="angular.min.js"></script>
<script
src="DIController.js"></script>
</body>
</html>
Controller
var DIApp = angular.module("DIApp", [])
Controller
var DIApp = angular.module("DIApp", [])
DIApp.service("employeeService",
function () {
return {
firstName: "firstName from
Service",
lastName: "lastName from
Service"
}
});
DIApp.controller("DIController",
function($scope, employeeService)
{
$scope.firstName = employeeService.firstName;
$scope.lastName = employeeService.lastName;
});Output
1 comment:
Angularjs online training
Post a Comment