Wednesday, September 2, 2015

Inject Controller to Application

In AngularJS Dependency Injection is achieved by injecting objects to the controller, also we can create different controller objects and inject them to the application. 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 controller and inject the controller to the application, this way all the data used in the application are fed from the injected controller, the injected controller can be changes or pass different controller objects to test 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: "Allan",
         lastName: "Donald"

var ControllerToInject = function($scope, employeeFactory)
    $scope.firstName = employeeFactory.firstName;
    $scope.lastName = employeeFactory.lastName;

ControllerToInject.$inject = ['$scope', 'employeeFactory'];
DIApp.controller('DIController', ControllerToInject);


Search Flipkart Products:

No comments: