Javascript – Injecting services into AngularJS directive controller directly


I understand how Angular dependency injection works with directives but wanted clarification on something. I have a dummy test directive as follows:

app.directive("test", [

  function() {

    return {
      restrict: "E",
      scope: {},
      controller: ["$scope", "$filter",
        function($scope, $filter) {
          var food = ["Apple pie", "Apple cobler", "Banana Split", "Cherry Pie", "Applesauce"];

          $scope.favorites = $filter('filter')(food, "Apple");
      template: "<div>{{favorites}}</div>"

This works fine and will filter the food array as expected. However I noticed if I inject the $filter service in the directive as follows, it still works:

app.directive("test", ["$filter",

  function($filter) {

    return {
      restrict: "E",
      scope: {},
      controller: ["$scope",function($scope) {...

My question: Is it better practice to inject services into a directive in the declaration line like so:

app.directive("test", ["$filter", function($filter) {

or in the controller line like this:

controller: ["$scope", "$filter", function($scope, $filter) {?

Is there no difference? Here is a Plunker of the directive code.

Best Solution

In this case, you're receiving the same service, so it likely doesn't matter too much. I personally prefer to keep them as localized as possible; if you don't need $filter in the link function or something like that, I'd just inject it into the controller.

In certain cases, this may also make it easier to mock dependencies during testing.

Related Question