EmmanuelDemey / EmmanuelDemey/eslint-plugin-angular

Manually Identify Dependencies (Y091)

Open
#41 0 comments 0 reactions 0 assignees View on GitHub
Rule
Dominant language
JavaScript
Stars
620
Forks
127
PR merge metrics
No merged PRs in 30d

Description

https://github.com/johnpapa/angularjs-styleguide/edit/master/README.md
- Use `$inject` to manually identify your dependencies for AngularJS components.

_Why?_: This technique mirrors the technique used by [`ng-annotate`](https://github.com/olov/ng-annotate), which I recommend for automating the creation of minification safe dependencies. If `ng-annotate` detects injection has already been made, it will not duplicate it.

_Why?_: This safeguards your dependencies from being vulnerable to minification issues when parameters may be mangled. For example, `common` and `dataservice` may become `a` or `b` and not be found by AngularJS.

_Why?_: Avoid creating in-line dependencies as long lists can be difficult to read in the array. Also it can be confusing that the array is a series of strings while the last item is the component's function.

``` javascript
/* avoid */
angular
.module('app')
.controller('Dashboard',
['$location', '$routeParams', 'common', 'dataservice',
function Dashboard($location, $routeParams, common, dataservice) {}
]);
```

``` javascript
/* avoid */
angular
.module('app')
.controller('Dashboard',
['$location', '$routeParams', 'common', 'dataservice', Dashboard]);

function Dashboard($location, $routeParams, common, dataservice) {
}
```

``` javascript
/* recommended */
angular
.module('app')
.controller('Dashboard', Dashboard);

Dashboard.$inject = ['$location', '$routeParams', 'common', 'dataservice'];

function Dashboard($location, $routeParams, common, dataservice) {
}
```

Note: When your function is below a return statement the $inject may be unreachable (this may happen in a directive). You can solve this by either moving the $inject above the return statement or by using the alternate array injection syntax.

Note: [`ng-annotate 0.10.0`](https://github.com/olov/ng-annotate) introduced a feature where it moves the `$inject` to where it is reachable.

``` javascript
// inside a directive definition
function outer() {
return {
controller: DashboardPanel,
};

DashboardPanel.$inject = ['logger']; // Unreachable
function DashboardPanel(logger) {
}
}
```

``` javascript
// inside a directive definition
function outer() {
DashboardPanel.$inject = ['logger']; // reachable
return {
controller: DashboardPanel,
};

function DashboardPanel(logger) {
}
}
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.