I am newbie to Angular.js , i have read that Controllers should not pollute the global namespace.
What does it really means
and why angular.module('SomeApp',[]).controller('SomeController', function($scope) {})
is the best way to add a controller?
Edit: Polluting the global namespace is not specific to Angular, but to Javascript (and actually any dynamic-typed language, where variables could appear or be redeclared in almost any scope).
Polluting the global namespace would make unavailable -actually: will override- certain names among modules.
Imagine I have a module A in 'a.js' where I declare:
mymodule = angular.module('A');
function Foo($s, $http){ ... };
foo = mymodule.controller('foo', ['$scope', Foo]);
Also imagine I included, beforehand, a script named 'utils.js':
foo = 3;
foo in a.js would override foo in my utils script. That is polluting the global namespace and that's why it's a bad idea (perhaps I actually NEEDED the foo var).
Want to have code like that instead of chaining the calls? use a closure:
/* a.js */
(function(){
var mymodule = angular.module('A');
function Foo($s, $http){ ... };
var foo = mymodule.controller('foo', ['$scope', Foo]);
})();
And so, you will not pollute the global namespace since each declaration is inside the anonymous function call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With