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 ?
Link: The link function deals with linking scope to the DOM. While defining a custom directive we have the option to define a link against which either we can define a function or we have the option to assign an object which will have pre & post function.
Dependency Injection is a software design in which components are given their dependencies instead of hard coding them within the component. It relieves a component from locating the dependency and makes dependencies configurable. It also helps in making components reusable, maintainable and testable.
In my opinion, we use controller when we need to share or reuse $scope data or we want directive interactive with each other. link is used for DOM manipulation tasks. This article compare the difference of controller and link in AngularJS directive with example, you could refer to it.
Which Component can be Injected as a Dependency In AngularJS? In Angular. JS, dependencies are injected by using an “injectable factory method” or “constructor function”. These components can be injected with “service” and “value” components as dependencies.
No, the link function has a predefined set of parameters.
function link($scope, $element, attrs, ctrl) { //Your method }
They are
required
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With