Daniel
Daniel

Reputation: 519

How to run two separate Angular js apps in the same page

New to Angular. I feel like I'm missing something obvious: Shouldn't I easily be able to run to separate AngularJs apps (modules) in the same html page? Something like this:

  <section ng-app="HelloWorldApp" ng-controller="HelloWorldController">
    Hello {{name}}!
  </section> 
  <br />
  <section ng-app="MyNameIsApp" ng-controller="MyNameIsController">
    My Name is {{FirstName}} {{LastName}}!
  </section> 

Javascript:

var HelloWorldApp = angular.module('HelloWorldApp', []);
HelloWorldApp.controller('HelloWorldController', function($scope) {
  $scope.name = 'World';
});

var MyNameIsApp = angular.module('MyNameIsApp', []);
MyNameIsApp.controller('MyNameIsController', function($scope) {
  $scope.FirstName = 'John';
  $scope.LastName = 'Smith';
});

This only runs the first module, while the second doesn't appear to do anything. I want to do this so that I can build reusable, encapsulated directives for multiple pages that don't have to name their modules the same thing.

Live Example: http://plnkr.co/edit/cE6i3ouKz8SeQeA5h3VJ


We ended up building small hierarchy of modules, however my original question can done, with just a bit of work (see below).

Upvotes: 33

Views: 20700

Answers (3)

dkavanagh
dkavanagh

Reputation: 51

You can specify any nested apps in the module def of the main one.

angular.module("myapp", ['statusapp', 'tickerapp']).controller(....

and in a separate file, you have the other apps defined. We're using a template engine which hides some of this, but you'll end up with HTML that contains nested ng-apps and javascript for each one that defines the module/controller. The code above is the trick to getting more than one bootstrapped.

Upvotes: 5

mfelix
mfelix

Reputation: 1834

According to the Angular docs for ngApp:

Use this directive to auto-bootstrap an application. Only one directive can be used per HTML document. The directive designates the root of the application and is typically placed at the root of the page.

Seems it's by design.

Upvotes: 7

TheHippo
TheHippo

Reputation: 63139

It is possible, but it requires a little bit coding by hand. You need to bootstrap the angular apps on your own. Don't worry, it is not that complicated

  • Do not add ng-app attributes in your HTML
  • Make sure you can fetch the DOM elements holding the app
  • When DOM is loaded you need to start the apps on your own: angular.bootstrap( domElement, ['AppName']);

Fork of you plunker which works: http://plnkr.co/edit/c5zWOMoah2jHYhR5Cktp

Upvotes: 48

Related Questions