Desorder Desorder - 25 days ago 8
AngularJS Question

Angularjs - single vs multiple ng-app?

I'm working on a web app. It's backended by Spring from controllers to database. Currently I handle page navigation using get methods from the Spring MVC controllers to access the pages.

I'm planning to use angular JS to do my UI work. I've looked up examples on how to do it and it's all good but I'm not sure about something...

ng-app

1- Should I use one per app or one per page or it doesn't matter?

2- If it doesn't matter when should I decide?

I see examples using it on the html tag and some others using in divs but I'm not sure how to decide that maybe due a lack of understanding about the framework.

Answer Source

angular docs

Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead. AngularJS applications cannot be nested within each other.

You can define multiple modules, which may have dependencies between them.

angular.module('Core', []);
angular.module('Module1', ['Core']);
angular.module('Module2', ['Core']);

Use the appropriate module on each page. How many modules should you have? It depends on how complex your application is and how do you want to structure it.

So yeah, if you've just started with angular I'd say don't bother too much with this. Put everything in one module and refactor afterwards. There are other, more tricky, parts about angular that you should be concerned about.

Also, you might want to take a look at this style guide.

EDIT:

just to be clear, the idea is to use one ng-app and choose the appropriate module to bootstrap the application depending on the area of your site (does not apply if you're building a single page application where you should have only one module responsible for bootstrapping your application)