0

I see a lot of Angular codes more like this. The following one is from their tutorial.

angular.module('phonecat', ['phonecatFilters', 'phonecatServices']).
  config(['$routeProvider', function($routeProvider) {
  $routeProvider.
      when('/phones', {templateUrl: 'partials/phone-list.html',   controller: PhoneListCtrl}).
      when('/phones/:phoneId', {templateUrl: 'partials/phone-detail.html', controller: PhoneDetailCtrl}).
      otherwise({redirectTo: '/phones'});
}]);

However, I am more familiar with like this;

var app = angular.module('phonecat', ['phonecatFilters', 'phonecatServices']);
app.config(function($routeProvider) {
  $routeProvider.
      when('/phones', {templateUrl: 'partials/phone-list.html',   controller: PhoneListCtrl}).
      when('/phones/:phoneId', {templateUrl: 'partials/phone-detail.html', controller: PhoneDetailCtrl}).
      otherwise({redirectTo: '/phones'});
}]);

I even want to define that function($routeProvider) { ...} as a variable, but I am not confident about that will work.

Is there a reason behind this to avoid global variable, in this case app.

Or it's just one of best practices in AngularJs community?

2 Answers 2

1

angular.module(..) returns a module, and you can;

  1. assign to a variable app(which is a global variable).
  2. or continue chaining it

You saw a lot of chained examples because it is in a single file.

You will also see a lot of examples using global variable 'app' or whatever, because codes needs to be organized to many files.

I recommend the first one if you make an single file example.
I recommend the second one if you make an actual app, which requires name spacing.

1

Namespacing is good. Best practive is using angular.value instead of global variables

app.value('myVariable', 'myValue')
   .controller('myController', function($scope, myVariable) {
       ...
    }); 
3
  • Maybe that helps you: javascriptweblog.wordpress.com/2010/12/07/… Commented Sep 18, 2013 at 21:52
  • y i like namespacing, but it seems AngularJS does not do that way, such as app.router, app.controller, app.filter, etc. Want to know reason behind it. There must be. Commented Sep 18, 2013 at 21:55
  • app.router or app.controller is a namespacing too. You have only one global variable(app) and every part of module belongs to app variable. Nothing new here, it's not Angular's finding. Commented Sep 18, 2013 at 21:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.