Reputation: 643
Reading angular docs on dependency injection, there are two minification-friendly methods to do this:
module.factory("MyStuff",['dependency',function(dep){...}])
$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:
MyStuff
directly:
new MyStuff(someOtherDependency).foo(...);
console.log(myStuffInstance)
Anything else I am missing?
Upvotes: 2
Views: 525
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