Tuesday, July 28, 2015

Dependency Injection in Angular?

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. The following is an example of normal controller implementation without using Dependency injection.

var app = angular.module("personApp", [])
app.controller("personController", function($scope) {
    $scope.firstName = "FName";
    $scope.lastName = "LName";
          $scope.fullName = function() {
                   return $scope.lastName + ", " + $scope.firstName;
          }
}); 

Notice that the values for the properties firstName and lastName are set in the controller, this is like hardcoding the values in the controller, Dependency Injection aims in eliminating this and supply the values for the properties from an external entity.

In AngularJS we can achieve this Dependency Injection in any of the following 3 ways.

Inject Angular Service to Controller
Inject Angular Factory to Controller
Inject Controller to Application

We shall see each of these in detail in the following posts.

Search Flipkart Products:
Flipkart.com

No comments: