0

I came across this tutorial.

http://justinvoelkel.me/laravel-angularjs-part-two-login-and-authentication/

The author used dependency injection to inject the login controller in app.js like this.

app.js:

var app = angular.module('blogApp',[
'ngRoute',
//Login
'LoginCtrl'
]);
app.run(function(){

});

//This will handle all of our routing
app.config(function($routeProvider, $locationProvider){

$routeProvider.when('/',{
templateUrl:'js/templates/login.html',
controller:'LoginController'
});

});

The login controller file looks like this.

LoginController.js:

var login = angular.module('LoginCtrl',[]);

login.controller('LoginController',function($scope){
$scope.loginSubmit = function(){
console.dir($scope.loginData);
}
});

I don't understand why the dependency injection is required here.

Here is my version of app.js and LoginController.js which works perfectly fine.

app.js:

var app = angular.module('ilapp', ['ngRoute']);

app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {

    $routeProvider.when('/login', {
        controller: 'LoginController'
    });

}]);

LoginController.js:

angular.module('ilapp').controller('LoginController', [function () {
    this.loginSubmit = function () {
        console.dir(this.loginData);
    };
}]);

Is there any advantage to the author's approach? What am I missing?

aBhijit
  • 5,261
  • 10
  • 36
  • 56

1 Answers1

0

First of all, both are correct way and it should work but you can choose any one method depends upon your project.

Approach 1

In your question, the first approach is modular way. Means, you can register a LoginController controller in a new module LoginCtrl. Here module name LoginCtrl is confusing. you can change the name as loginModule. This approach is helpful for you to organize the files structure for your big application. Also, look this post Angular - Best practice to structure modules

var login = angular.module('loginModule',[]);

login.controller('LoginController',function($scope){
 $scope.loginSubmit = function(){
 console.dir($scope.loginData);
 }
});

var app = angular.module('blogApp',[
 'ngRoute',
 'loginModule'
]);
app.run(function(){
});

//This will handle all of our routing
app.config(function($routeProvider, $locationProvider){
 $routeProvider.when('/',{
 templateUrl:'js/templates/login.html',
 controller:'LoginController'
});

});

Approach 2

If your application contains minimal pages and no need to split multiple modules, then you can write all your controllers in app.js itself

Community
  • 1
  • 1
Asik
  • 7,967
  • 4
  • 28
  • 34