What is the most effective way to divide an AngularJS application into smaller modules? For instance, if I have a blog post with commenting functionality, I could potentially separate them into modules like "posts" and "comments", rather than having all the logic in one large module.
I attempted to initialize both modules in separate DOM elements and implement routing for each module. However, I encountered some issues:
- Since it's a single-page application, the comments module is bootstrapped even on pages where it isn't needed.
- Due to the restriction of using multiple ng-views within ng-app, I had to create wrappers for my modules in index.html and then bootstrap them. This approach feels somewhat incorrect. Where and how should these modules be initialized?
- Any suggestions for handling routing? Should it be spread across modules or consolidated somehow? (e.g., creating a "blog" module that includes "posts" and "comments" as dependencies might make defining "/post/:id" routing challenging).
index.html
<div class="post"><ng-view></ng-view></div>
<div class="comments"><ng-view></ng-view></div>
javascript.js
angular.module('posts', []).config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
'template': 'Showing all the posts',
'controller': 'postCtrl'
})
.when('/post/:id', {
'template': 'Showing post :id',
'controller': 'postCtrl'
});
}]);
angular.module('comments', []).config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/post/:id', {
'template': 'Showing post :id comments',
'controller': 'CommentsCtrl'
});
}]);
angular.bootstrap($('.post'), ['posts']);
angular.bootstrap($('.comments'), ['comments']);