Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split AngularJS application into smaller modules and handle routing correctly?

What would be the best way to split AngularJS application into smaller pieces/module? For example if I have a blog post and commenting enabled for that, I think I could break it down to modules like "posts" and "comments"(?) (maybe not the best example, but the idea is to split the application logic into separate modules rather than building a huge one-module-app).

I've tried to bootstrap both modules in the separate DOM nodes and use routing in both of the modules accordingly. There are few problems:

  • As a "single-page" application I'm bootstrapping comments module to be used even on the front page even though it's not used there.
  • Since I'm not able to use multiple ng-views inside ng-app, I'm forced to write all the wrappers for my modules in the index.html view and bootstrap them? Should it be like that? Seems a bit wrong. How/where should I bootstrap those?
  • Are there any tips for the routing? Should I spread those in the modules or should I combine them all together somehow? (creating one "blog" module to include "posts" and "comments" modules as dependencies would still make it hard to define for example the "/post/:id" routing..?)

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']);
like image 996
acoder Avatar asked Mar 08 '13 12:03

acoder


People also ask

Can an Angular app have multiple modules?

So now, you need to follow some simple steps to use multiple modules in an Angular application. Create a simple application using Angular CLI. If you are going to use Angular for the first time, click here. I am going to create an application which contains three modules: App, Employee, Admin, Home.

How does the AngularJS application route?

Application routes in AngularJS are declared via the $routeProvider, which is the provider of the $route service. This service makes it easy to wire together controllers, view templates, and the current URL location in the browser.

Which module is required to configure route details in an AngularJS application?

AngularJS ngRoute module provides routing, deep linking services and directives for angular applications.

How many phases are there to split modules life cycle in AngularJS?

Now that you understand the components involved in an AngularJS application, you need to understand what happens during the life cycle, which has three phases: bootstrap, compilation, and runtime.


4 Answers

I would divide the app in "view modules" and these sub modules.

Then I use the $routeProvider to switch between the views. I define the different routing config in each module.

If I need further submodules, I load these with ng-include.

/* App Module */

angular.module('MyApp', ['MyApp.home', 'MyApp.blog'])
.config( function myAppConfig ( $routeProvider ) {
    'use strict';
    $routeProvider.otherwise({ redirectTo: '/home' });
});


/* home Module */

angular.module('MyApp.home', [])
.config(['$routeProvider', function config( $routeProvider ) {
  $routeProvider.when('/home', {
    controller: 'HomeController',
    template: '<p>This is my Home</p>'
  });
}]);

I created a little repository on github to explain this.

like image 111
N0rdl1cht Avatar answered Oct 07 '22 17:10

N0rdl1cht


You can define routes in the submodules:

angular.module('app', ['ngRoute', 'app.moduleX'])
.config(function($routeProvider, $locationProvider) {
  $routeProvider.when('/home', {
    templateUrl: 'partials/home.html',
    controller: 'HomeCtrl'
  });

  //Handle all exceptions
  $routeProvider.otherwise({
    redirectTo: '/home'
  });
})

angular.module('app.moduleX', []).config(function($routeProvider) {
  $routeProvider.when('/settings', {
    templateUrl: 'partials/settings.html',
    controller: 'SettingsCtrl'
  });
})

I also wrote a blog post about this topic.

like image 30
krtek Avatar answered Oct 07 '22 18:10

krtek


We're doing something similar with a portal app and sub-apps. A few things we've discovered:

  1. Only one "app" can have routes and routeParams. Because of this, if the "sub-app" needs access to the $routeParams, you either have to go "old school" for URL parsing, or use an event service.
  2. Speaking of events, there is no Angular service for the apps to communicate, so you'll need to roll your own event service talking to root scope for both apps and inject it into both apps.
  3. I can't see where we used ng-view for the "sub-app". Apparently bootstrapping directly to an element works similarly.
  4. Because only one app can have routes, the apps should be bootstrapped in order. So something like this:

    $( function () {
    
        $.when(angular.bootstrap($('.post'), ['posts'])).done( function() {
            console.log('POSTS: bootstrapped');
    
            //Manually add the controller to the comments element. (May or may not be  
            //necessary, but we were doing something that required it to work.)
            $('.comments').attr('ng-controller', 'CommentsCtrl');
    
            $.when(angular.bootstrap($('.comments'), ['comments'])).done( function() {
                console.log('COMMENTS: bootstrapped');
            });
    
        });
    });
    
like image 33
Sharondio Avatar answered Oct 07 '22 17:10

Sharondio


I hope you can use "ui-router" routing module.

Here is good tutorial for this http://www.ng-newsletter.com/posts/angular-ui-router.html

like image 44
Premchandra Singh Avatar answered Oct 07 '22 18:10

Premchandra Singh