heyred
heyred

Reputation: 2051

Splitting AngularJS controllers into multiple files

I have a cross-platform enterprise app built using Onsen UI and AngularJS. However, the app is fast growing in size and is becoming confusing and difficult to manage. Up to now I have been able to manage all the apps controllers in 1 app.js file and the app is working perfectly. But I want to split my controllers into different .js files e.g. login.js, registration.js. to make it more manageable as the app grows.

I have found THIS solution on SO (the marked answer) but I have trouble implementing it. Equally the answer by @jason328 on the link looks very elegant, but again I get stuck implementing that with my code.

In my main new app.js file I have the module as follows:

angular.module('myApp.controllers', ['onsen']);

And then in e.g. login.js I setup my module as below:

angular.module('myApp.controllers').controller('LoginController', ['$scope', '$http', function($scope, $http)
{
    // All the login logic goes here
}]);

This does not work as none of the pages are displayed. When I have this setup in the original app.js file though, the app works perfect (original code below).

var app = angular.module("myApp", ['onsen']);
// Manages the state of the login.html screen
app.controller("LoginController", function($scope, $http)
{
    // All the login logic goes here
});

My issue lies with ['onsen'] in the new app.js I assume? But how do I include it in the SO solution I am trying to implement?

Upvotes: 2

Views: 2419

Answers (2)

Paulo Silva
Paulo Silva

Reputation: 11

You can turn them into modules, like @nicous mentioned and import them on the main app.js wherever you have to use them, then you can use webpack or any other bundler to generate your bundle for you. This way you won't need to add all of them to the html file.

Upvotes: 1

nicous
nicous

Reputation: 411

There's an other way to do this. You can make a module for each file and add them to the myApp module, like this:

app.js

var app = angular.module("myApp", ['onsen', 'loginControllers', 'otherController']);

login.js

var login = angular.module("loginControllers", []);
login.controller("LoginController", function($scope, $http)
{
    // All the login logic goes here
});

other.js

var other = angular.module('otherControllers', []);
other("OtherController", function($scope, $http)
{
    // All the other logic goes here
});

Make sure you have all the scripts added to your index.html.

Upvotes: 2

Related Questions