Forward Advance Learning

Angular Modules.

Thus far we have put all our code into a single module, which we have called 'app'.

angular.module('app', [])

This is fine for smaller apps, but when things start to get larger, we will want some more organisation.

We may also wish to include third party code. It would be useful if we could simply include other modules into our app module.

The square braces that we pass to our module can include a list of names of other modules, like so:

angular.module('app', ['cats', 'dogs']);

We can then declare code in these other modules:

angular.module('cats', [])
.controller('catsController', function() {});
.service('catsService', function() {})
angular.module('dogs', [])
.controller('dogsController', function() {});

Namespacing still matters

Including a module in another module makes everything in that module available globally. There is no subtlety here. The example above, could just as well be written like this:

angular.module('app', [])

It doesn't matter how deep the module tree you make, everything is available globally to your whole app.

This means that namespacing is still a big deal.

How to namespace controllers.

I would typically name an app component something like:


So for example:

  • CatsController
  • CatsAdminController
  • CatsService (or just cats)

You may wish to go further and prepend the name of your app:

  • MyappCatsController
  • MyappCatsAdminController
  • MyappCatsService (or just cats)

Some people use dots, though this will prevent you from using the injector shorthand

  • 'Myapp.Cats.Controller'
  • 'Myapp.Cats.Admin.Controller'
  • 'Myapp.Cats.Service (or just cats)'

You can then inject using the longhand square brace injector syntax like this:

angular.module('app', ['cats'])
.controller('appController', [
function(cats) {
// make use of the cats service here

Exercise - NgDialog

We are going to inject the ngDialog service into a controller. This will allow our controller to create popup dialog boxes.

First go here and grab the ng-dialog.js. Link it in the header of your document in the usual way with a script tag.

Now download the CSS files: ng-dialog.css and ng-dialog-theme-plain.css. Link them using link tags.

Include it in your app.

We need to include ngDialog as a dependency of the app, like this:

angular.module('app', ['ngDialog'])

Inject into your controller.

Create a little controller and use the ng-controller directive to hook it to the DOM.

<div ng-controller="myController">

Inject the ngDialog service into your controller.

.controller('myController', function($scope, ngDialog) {

You now have access to Call this according to the documentation to create a dialog box when the page loads:

template: '<p>my template</p>',
className: 'ngdialog-theme-plain',
plain: true

Exercise - Extension

Create a form. Create a method on scope that opens the dialog. Call the method when the button is pressed.