Borv Borv - 4 months ago 18
AngularJS Question

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:

  • Inline Array Annotation:


  • The

    function MyStuff(dep) {...}
    MyStuff.$inject = ['dependency'];

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

Hence the question:

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

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

  • Creating instances of

    new MyStuff(someOtherDependency).foo(...);

  • Having function name in

Anything else I am missing?


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