Gaurav Aggarwal Gaurav Aggarwal - 6 months ago 28
Javascript Question

which is best to `mainApp.config(['$routeProvider', function($routeProvider)` and `mainApp.config(function($routeProvider)`

I have just started learning angularJS but i can notice the same thing so many time that at some places when we start writing a function in angularJS i noticed that some people define the function they are going to use like this

var mainApp = angular.module("mainApp", ['ngRoute']);
mainApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.

when('/addStudent', {
templateUrl: 'addStudent.htm',
controller: 'AddStudentController'
}).

when('/viewStudents', {
templateUrl: 'viewStudents.htm',
controller: 'ViewStudentsController'
}).

otherwise({
redirectTo: '/addStudent'
});
}]);


But the same function is working fine if we just write the function without this
['$routeProvider'
like this

var mainApp = angular.module("mainApp", ['ngRoute']);
mainApp.config(function($routeProvider) {
$routeProvider.

when('/addStudent', {
templateUrl: 'addStudent.htm',
controller: 'AddStudentController'
}).

when('/viewStudents', {
templateUrl: 'viewStudents.htm',
controller: 'ViewStudentsController'
}).

otherwise({
redirectTo: '/addStudent'
});
});


I know there is no big difference when coming to code writing but still is there any difference in both the ways. If yes, then is it about minifying? and is there any negative point other that that of using it?

Thanks in advance!

Answer
mainApp.config(['$routeProvider', function($routeProvider) {
}]);

This type define a controller is callled Inline Array Annotation. And It is min-safe. min-safe mean if you minify your code then it will still work.

mainApp.config(function($routeProvider) {
});

This type of define a controller is called 'Implicit Annotation'. And its not min-safe. min-safe mean if you minify your code then it will not work.

And there a another way to declare a controller $inject Property Annotation

var MyController = function($scope, greeter) {
  // ...
}
MyController.$inject = ['$scope', 'greeter'];
someModule.controller('MyController', MyController);

read more info click here

Comments