Angular - function in dependency or dependency in function params?

75 views Asked by At

I'm new to angular, every tutorial is doing things differently and it's confusing. I managed to understand best practices and follow them. But check this out:

enter image description here -See how guys at Microsoft are putting $scope and function in dependency brackets.

On the other hand,this guy Egghead is doing this:

enter image description here

He is putting dependencies in function parameters.

Whats the difference and whats the best practice?

3

There are 3 answers

0
Explosion Pills On BEST ANSWER

These effectively do the same thing and are different forms of Dependency Annotation provided by AngularJS. The latter will not work if the code is minified because it would become .controller('TodoListController', function (a, b) { and there is no a service. The former still has the '$scope' string, so Angular knows what service to inject.

You can use the ng-annotate library to produce minification-proof code from implicitly annotated code.

I find implicit annotation easier to read and of course it is easier to write. If you need to minify your code, you can include a build with ng-annotate as an additional step anyway, so it shouldn't matter. If you don't need to minify your code and you're just writing non-production examples, there's no need to use inline array annotation anyway.


This is unrelated, but injecting $scope is needed a lot less now because of Angular's controller as syntax.

0
rdthijssen On

It's a best practice to put dependency's inside the dependency brackets. Because otherwise the code wouldn't be able to be minimized on deployment.

When using dependency brackets the parameters passed to this controller would always resolve to the string names inside the brackets. When you're not doing this (when looking at the Egghead example) the sharedScope parameter would not be able to be renamed to a shorter name (to minimize) because Angular wouldn't know what dependency it should inject.

0
Nikola Zivkovic On

Go with Microsoft example, it's good thing to do that, when you decide at one point to minify your code, then this type of writing dependencies will go without errors (for minify)...