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 ng-app="DIApp">
    <meta charset="utf-8">
    <title>AngularJS - Basic</title>
<div ng-controller="DIController">
          First Name: <input type="text" ng-model="firstName"><br>
          Last Name: <input type="text" ng-model="lastName"><br>
    <script src="angular.min.js"></script>
          <script src="DIController.js"></script>

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;



Search Flipkart Products:

No comments: