In my view, the first code snippet is superior and Angular actually recommends that approach:
https://docs.google.com/document/d/1XXMvReO8-Awi1EZXAXS4PzDzdNvV6pGcuaF4Q9821Es/pub
Organizing code into modules is a great practice. In my apps, I typically structure them like this:
modules
|--home
home-controller.js
home.js
home-service.js
home.html
|--user
user-controller.js
user.js
user-service.js
user.html
This way, each module's code is neatly arranged in its own file within a dedicated directory, making organization much simpler.
A typical module file (e.g., home.js) using require.js might look like this:
define(function(require) {
var angular = require("angular");
var homeController = require("modules/home/home-controller");
var homeService = require("modules/home/home-service");
var homeModule = angular.module("Home", []);
homeModule.controller("HomeCtrl", homeController);
homeModule.service("HomeService", homeService);
return homeModule;
});
The advantages of this approach include:
Ensuring clean organization by grouping related files together within directories, avoiding the need to search all over for specific files when working on a feature.
Keeping code contained in individual files, preventing a massive 'controllers' file with all controller code lumped together.
Simplifying module bundling for reuse across multiple applications/systems through easy minification/packaging of directories.
Facilitating efficient unit testing by isolating tests to specific modules only, reducing load times and enhancing test focus compared to loading all controller code at once.
Regarding your second question, app.js
typically serves as the main module for an Angular application, with other modules added as dependencies. This allows for modular expansion of functionality. The actual controllers.js
file would be loaded either via a script tag or AMD/CommonJS loading before being added as a dependency to the main app module.
In contrast to the first example, grouping modules by type (e.g., controllers, services) instead of by feature can lead to scattered features and increased difficulty in locating code components. It also results in unnecessary loading of all controllers when testing specific ones.
Following Google/Angular's style suggestions involves grouping modules by feature (e.g., user directory, home directory) rather than by file type. This promotes better organization and efficiency in development.
The ability to reference phoneCatControllers
as a module dependency stems from Angular's bootstrap process during onDOMContentLoaded, where all scripts are loaded before application initialization. Manual bootstrapping is possible with tools like RequireJS, but in your scenario, Angular handles the bootstrapping after all script loading.
For further details, refer to:
https://docs.angularjs.org/guide/bootstrap