Get Your AngularJS Controllers Out of the Global Namespace

Get Your AngularJS Controllers Out of the Global Namespace

If you have learned AngularJS from the tutorials or documentation area on the AngularJS website, then you may be learning to setup your controllers in a way that pollutes your global namespace.

The second tutorial on the AngularJS site (Angular Templates) has some code that looks like this:

function PhoneListCtrl($scope) {
  $scope.phones = [
    {"name": "Nexus S",
     "snippet": "Fast just got faster with Nexus S."},
    {"name": "Motorola XOOM™ with Wi-Fi",
     "snippet": "The Next, Next Generation tablet."},
    {"name": "MOTOROLA XOOM™",
     "snippet": "The Next, Next Generation tablet."}
  ];
}

That will work, but notice that function is declared in the global namespace without any namespacing.  If you've been using javascript a while, then you know this is a bad practice and can get tricky for larger sites as objects start to collide.

The good news is that AngularJS provides a way to namespace your entire app using modules. If we simply modified the code in that tutorial to:

angular.module('MyPhoneListApp', []).controller('PhoneListCtrl', function ($scope) {
  $scope.phones = [
    {"name": "Nexus S",
     "snippet": "Fast just got faster with Nexus S."},
    {"name": "Motorola XOOM™ with Wi-Fi",
     "snippet": "The Next, Next Generation tablet."},
    {"name": "MOTOROLA XOOM™",
     "snippet": "The Next, Next Generation tablet."}
  ];
});

Note the [] in the second parameter of the module declaration.  That is needed when creating a module and is used to load in any dependencies from other AngularJS modules that you or others have created.

Then in your markup simply change your ng-app declaration to be more specific and tell it your module: np-app="MyPhoneListApp".

Author

Jason Prothero

comments powered by Disqus
back to top