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
745 views
in Technique[技术] by (71.8m points)

angularjs - Why are global functions considered "wrong" in Angular 1.3

Traditionally I have managed my Angular code like this

//File 1
angular.module('name',[])
//File 2
function TestController(){

}
TestController.prototype.// inherited stuff
angular.module('name').controller('testController',TestController);

This worked great and allowed me to partition my files easily. Now I try to upgrade to 1.3 and get the infamous...

Error: [ng:areq] Argument 'TestController' is not a function, got undefined 

Of course this is due to this change which claims a desire to clean up the way people write code. What about this pattern is more complex? Is there a way to maintain this pattern without changing the global settings?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

There is actually a comment on the page you linked to that had a fairly solid explanation.

Global controllers refer to your controllers being defined as function on the window object. This means that they are openly available to conflict with any other bit of JavaScript that happens to define a function with the same name. Admittedly, if you post-fix your controllers with ...Controller then this could well not happen but there is always the chance, especially if you were to use a number of 3rd party libraries. It is much safer to put these controller functions inside the safety of a module. You then have more control over when and where this module gets loaded. Unfortunately controller names are global across an individual Angular app and so you still have the potential for conflict but at least you can't clash with completely different code in the JavaScript global namespace.

So the idea is that global controller functions could conflict with any other global function in any javascript you use. So to eliminate the chance of a conflict with your own code or a third-party script, not using global controllers makes your code safer and more consistent.

As mentioned in the comments by @Brett, you can use IIFE around your prototyping. Here is an update of your plunk that uses that. The main change just looks like this.

(function() {
  TestController.prototype.name = 'World'
})();

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

...