</>
Skip to content
AngularJS lessons (16/28)

AngularJS — Dependency Injection

What is DI?

Dependency Injection provides dependencies to components from outside.

Injection Types

// Implicit (minification breaks this)
app.controller('MyController', function($scope, $http) {});

// Inline array notation (safe)
app.controller('MyController', ['$scope', '$http', function($scope, $http) {}]);

// $inject property
MyController.$inject = ['$scope', '$http'];
function MyController($scope, $http) {}

DI in Services

app.factory('DataService', ['$http', function($http) {
  return {
    getData: function() {
      return $http.get('/api/data');
    }
  };
}]);

DI in Directives

app.directive('myDirective', ['$http', function($http) {
  return {
    link: function(scope, element, attrs) {
      // $http available here
    }
  };
}]);

Minification Safe

// Before minification
app.controller('MyCtrl', function($scope, $http) {});

// After minification (broken)
app.controller('MyCtrl', function(a, b) {});

// With array notation (safe)
app.controller('MyCtrl', ['$scope', '$http', function(a, b) {}]);

Mini Practice

  1. Use array notation
  2. Inject services
  3. Test with minified code
  4. Create injectable components

Up Next

Continue with Filters — AngularJS filters.

Related Topics

Frequently Asked Questions about Dependency Injection

What is Dependency Injection in AngularJS?

Dependency Injection is a fundamental concept in AngularJS. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Dependency Injection?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Dependency Injection.

Why is Dependency Injection important in AngularJS?

Dependency Injection is essential for AngularJS development. Understanding this concept will help you write better code and solve real-world problems more effectively.