Borv
Borv

Reputation: 643

Any difference between angular $inject property and inline array annotation?

Reading angular docs on dependency injection, there are two minification-friendly methods to do this:

The inline one (first) is recommended. In one of my projects the style guide insists on the use of $inject property. I also see $inject property form quite often in open source code.

Hence the question:

What are the practical or technical benefits of using the $inject property form?

From the top of my head I came up with two, and they don't look very legit:

Anything else I am missing?

Upvotes: 2

Views: 525

Answers (1)

Bryan Chen
Bryan Chen

Reputation: 46598

You should be using ng-annotate. If you are using build tool (you should), use the ng-annotate plugin with your build tool.

The main benefit of second approach is that it is module friendly.

class MyClass {
    constructor($q) {}
}

MyClass.$inject = ['$q']

module.exprots = MyClass

You can use it like normal class

const MyClass = require('./myclass')
const foo = new MyClass($q)

or give it to angular

angular.service('MyClass', MyClass)

You can't really do

module.exports = ['$q', MyClass]

because it will make require('./myclass') unusable outside of angular


But if you are not using module or OOP, first approach is easier

angular.service('MyClass', ['$q', function ($q) {}])

There is no need to make a class for it

Upvotes: 2

Related Questions