Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
19
rated 0 times [  22] [ 3]  / answers: 1 / hits: 16076  / 10 Years ago, mon, august 4, 2014, 12:00:00

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.


More From » angularjs

 Answers
5

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.


[#69931] Friday, August 1, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
catrinas

Total Points: 587
Total Questions: 100
Total Answers: 105

Location: Rwanda
Member since Thu, Feb 10, 2022
2 Years ago
;