26

In:

module.directive 'name', ->
  (scope, element, attr) ->
    # Whatever implemenation

Do the scope, element and attrs parameters of the link function rely on name-inferred Dependency-Injection? If yes, how can I make them minification proof ?

Or do they rely on good old arguments order for what's passed into them ?

Rubens Mariuzzo
  • 28,358
  • 27
  • 121
  • 148
ejoubaud
  • 5,013
  • 6
  • 37
  • 39

2 Answers2

44

No, the link function has a predefined set of parameters.

function link($scope, $element, attrs, ctrl) {
    //Your method
}

They are

  1. Scope of the element
  2. The element itself (jquery/mini jquery wrapped)
  3. Attribute set of the element
  4. Any controllers used in required
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • 1
    What about minification? `['$scope', '$element', '$attrs', function($scope, $element, $attrs) {... }` – Clev3r Jan 08 '14 at 14:02
  • 12
    The link function does not require the minification array syntax. – Timothy Lee Russell Jan 22 '14 at 05:32
  • Can you tell us more about the controller part? Is it an object with a value for each controller? – heneryville May 30 '14 at 16:02
  • If I am seeing the following, what would the 5th parameter be? `link: function($scope, $element, attrs, controller, e) {}` – Danny Bullis Jun 19 '15 at 19:58
  • It's transclude. function(scope, element, attrs, ctrl, transclude) {} where it's a function that returns the contents when the directive has "transclude: true" – user1212212 Sep 10 '15 at 06:17
  • I think it is important to note that 4 (ctrl) will be the directives controller (and all properties defined on it `this.test = 42;`) if `required` is not present but a controller is. – Victorio Berra Feb 24 '17 at 15:53
22

If you want to use DI with a directive (as I did), put the arguments to be injected in the directive factory function instead of the link function:

module.directive('name', function($timeout) {
    return function(scope, element, attrs) {
        ...
    };
});

To allow for minification, put the function argument in an array like you do for controllers:

module.directive('name', ['$timeout', function($timeout) {
    return function(scope, element, attrs) {
        ...
    };
}]);

See the current time example in the docs.

Edit: See here for a demo that injects the $timeout service. You can do the same thing when returning a directive (e.g. return {restrict: 'E', link: function() {...}}) object instead of a function.

z0r
  • 8,185
  • 4
  • 64
  • 83