Not polluting global with angularjs

angularjs, javascript

Solution

One of the ways around it is to define it within Angular itself such as the way you described. In other words:

`angular.module('YourApp').controller('ControllerName', function($scope) {}) `

I have confirmed the above method doesn't pollute the global namespace.

Edit: You also don't need to use `<div ng-controller="myApp.UserController">` as you could define myApp in the attribute ng-app: `<body ng-app="myApp">` That way you could call the ng-controller without prefixing myApp every time.

Problem

In angularjs, we define our controllers into `window`. While this would not create name clashes with other `js` modules and plugins, it is still not a good practise: a single application should expose a single object to the global namespace. This is the usual way, defined in `window`: ``` function UserController($scope) { ... } ``` HTML: ``` <div ng-controller="UserController"> ``` This is what I think of: ``` myApp.UserController = function ($scope) { ... }; ``` So in that case, I should be initiating controller from html like this ``` <div ng-controller="myApp.UserController"> ``` What do you think?

Original source