Tuesday, July 28, 2015

Inject Angular Service to Controller

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 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", [])

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




Search Flipkart Products:
Flipkart.com

No comments: