Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 915
TrazeK Avatar asked Aug 04 '14 03:08

TrazeK


Video Answer


2 Answers

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.

like image 163
Michelle Tilley Avatar answered Sep 23 '22 13:09

Michelle Tilley


You can do this also. Much better way by splitting directive and its controller in a single file. Or you can write in separate files. But, better understand

app.directive('throbberDirective', 
[   
    function(){
        return {
            restrict: "EA",
            templateUrl: "common/utils/throbbers/throbber.html",
            controller: throbberController
        }
    }
]);
app.controller('throbberController', throbberController);
throbberController.$inject = ['$scope', '_$ajax'];
function throbberController($scope){
     $scope.throbber = _$ajax.getThrobberConfigs();
     $scope.throbber.templateName = $scope.throbber.templateName;

}
like image 27
Mr_Perfect Avatar answered Sep 24 '22 13:09

Mr_Perfect