Wednesday, September 2, 2015

Inject Angular Factory 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 factory and inject the factory to the controller, this way all the data used in the controller are fed from the factory, the factory can be changes or pass different factory 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.factory("employeeFactory", function () {
    return {
         firstName: "John",
         lastName: "David"
   }
});

DIApp.controller("DIController", function($scope, employeeFactory)
{
    $scope.firstName = employeeFactory.firstName;
    $scope.lastName = employeeFactory.lastName;


});

Output









Search Flipkart Products:
Flipkart.com

No comments: