Book Image

Learning Single-page Web Application Development

Book Image

Learning Single-page Web Application Development

Overview of this book

Table of Contents (15 chapters)
Learning Single-page Web Application Development
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Understanding dependency injection


Dependency injection is a common software design pattern and widely used in AngularJS; it is similar to what we have in the Express framework using require(). You just need to add the services as parameters to controllers, directives, or functions. Many of these items will depend on others to work. For example, a controller request to the server will need the $http service, and this service has to come from somewhere.

To facilitate this configuration, AngularJS provides three ways to declare dependencies:

  • Directly using the parameters of a function, as we can see in the following example:

    function UserController($scope, $http, $resource, $ownservice) {
      var user;
    
      $scope.user = {
        name: "Fernando",
        age: "25"
      }
    }
  • Using an array, as shown here:

    User.controller ('UserController', ['$scope','$http' function ($scope, $http) {...}]);
  • Using the $inject property, as follows:

    UserController var = function ($scope, $http) {...};
    UserController $ inject = ['...