Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

javascript - Why wouldn't you use explicit annotations when defining controllers in AngularJS?

I am new to AngularJS and learning about the two styles of writing controller functions. It seems as though the only reason someone would not use explicit annotations is to save time, which doesn't seem like a good reason. And being able to minify/obfuscate code seems like a requirement I would want to keep in any application.

Also note that I am not asking which is better or asking for a debate. I am asking for what reasons (or in what situation) it would be more beneficial to not use explicit annotations.

Example of what I'm talking about:

module('myApp').controller('MyController', function($scope) {});

vs.

module('myApp').controller('MyController', ['$scope', function($scope) {}]);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The inline array annotation is simply a workaround over Javascript limitations to allow Angular code to be minified and not to stop working. But it isn't a great solution because if forces you to duplicate your code. And we all know how bad duplicate code is. Angular documentation itself acknowledges that:

When using this type of annotation, take care to keep the annotation array in sync with the parameters in the function declaration.

It's way too easy to add a new dependency and forget to add the corresponding annotation. Or to reorder the arguments and forget to update the list of annotations. Trust me. Been there, done that.

Fortunately there are tools developed by smart people that take that burden off our shoulders by taking care of annotating the code automatically. Probably the most known is ng-annotate, as mentioned by @pankajparkar. All you have to do is plug it into your build process and your code will be correctly annotated.

To be honest, I find it really odd that Angular documentation recommends against following this approach.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...