"Controllers polluting the global namespace", what does it mean in Angular

I'm new to Angular.js

, I read that controllers shouldn't pollute the global namespace.

What does it mean mean

and why angular.module('SomeApp',[]).controller('SomeController', function($scope) {})

is the best way to add a controller?

+3


source to share


2 answers


Edit . Global namespace pollution is not specific to Angular, but to Javascript (and in fact any dynamically typed language where variables can appear or update in almost any scope).

Pollution of the global namespace will be inaccessible - in fact: 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 that I have included a script ahead of time called 'utils.js':



foo = 3;

      

foo

in a.js will override foo

in my utils script. This pollutes the global namespace and why is it a bad idea (maybe I really NEEDED foo var).

Do you want to have a code like this instead of a call chain? use closure:

/* a.js */
(function(){
    var mymodule = angular.module('A');

    function Foo($s, $http){ ... };
    var foo = mymodule.controller('foo', ['$scope', Foo]);
})();

      

This way, you won't pollute the global namespace, since every declaration is inside an anonymous function call.

+3


source


This format that you used

angular.module('SomeApp',[]).controller('SomeController', function($scope) {})

      

does not pollute the global namespace.


In this format:

Javascript



function UserController($scope) { ... }

      

Html

<div ng-controller="UserController">

      


This is because the controller function is globally accessible outside of the angular scope

+2


source







All Articles