Why global functions are 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 split files easily. Now I'm trying 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 talks about wanting to clean up the way people write code. How about this pattern is more complicated? Is there a way to save this template without changing global settings?

+3


source to share


2 answers


There is actually a comment on the page you linked to and it had a pretty clear explanation.

Global controllers refer to your controllers, which are defined as a function on a window object. This means that they are openly available for conflict with any other piece of JavaScript that has the same name. Admittedly, if you are controllers with ... Controller then this may very well happen, but there is always a chance, especially if you use a number of 3rd party libraries. It is much safer to put this controller to perform the safety functions of the module. Then you have more control over when and where this module is loaded. Unfortunately, controller names are global in a single Angular application, and you still have the potential for conflict, but at least you can't run into completely different code in the global JavaScript namespace.

So the idea is that global controller functions can conflict with any other global function in whatever javascript you use. Therefore, to eliminate the possibility of conflict with your own code or third party script, by not using global controllers, your code will be safer and more consistent.



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

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

      

+3


source


What comes to my mind is two things:

1), so the functions will not be stored in memory any longer than they should.



2) if you minify your code minifyer will have to generate new names for all global objects, which is very small if you have a small project, but will be a problem if it is not.

It should also disallow tests to modify unnecessary data.

0


source







All Articles