Borv Borv - 1 month ago 11
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:

    module.factory("MyStuff",['dependency',function(dep){...}])

  • The
    $inject
    property:

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



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:


  • Creating instances of
    MyStuff
    directly:

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

  • Having function name in
    console.log(myStuffInstance)



Anything else I am missing?

Answer

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