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 ...

Get Learning Single-page Web Application Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.