Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

different ways to define angular module

Tags:

angularjs

so today i search over internet i found something interest. so normally i define the angular module like this

var app = angular.module('myApp',[]);
app.controller('myCtrl',function($scope){ 
//some code
})

or even like this

 angular.module('myApp',[])
    .controller('myCtrl',function($scope){ 
    //some code
    })

but today i found out there is a another way to define the angular module

(function(app){

})(angular.module('myApp',[]))

so what is the different between those initialization. is there most efficient way. i try to search this over the internet but could't find out a solution. thanks guys

like image 352
Sachila Ranawaka Avatar asked Apr 30 '26 18:04

Sachila Ranawaka


1 Answers

First & second declarations doesn't have any major difference. Third option is recommended.

  1. You are just saving the return value from angular module setter method and reusing it through a global variable.

  2. Instead of using a global variable for storing module reference, we directly declare controller on the returned value. This mode is called "method chaining"

  3. Here we making use of angular's getter syntax, which will return the module reference. Getter syntax together with an immediately invoked function expression (IIFE) makes sure that you are not polluting global namespace. And this is the preferred way of writing controllers, services etc.

For best practices in angular, have a look at John Papa's style guide for AngularJS

like image 159
Aswin S Avatar answered May 02 '26 12:05

Aswin S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!