Chapter 2. Basic AngularJS Directives and Controllers

We saw in Chapter 1 how to create a very simple and trivial AngularJS application, which was basically the “hello world” of the AngularJS world. In this chapter, we will expand on that example.

We explore AngularJS modules and controllers, and create our very own controllers. Then we use these controllers to load data or state into our application, and manipulate the HTML to perform common tasks such as displaying an array of items in the UI, hiding and showing elements conditionally, styling HTML elements based on certain conditions, and more.

AngularJS Modules

The very first thing we want to introduce is the concept of modules. Modules are AngularJS’s way of packaging relevant code under a single name. For someone coming from a Java background, a simple analogy is to think of modules as packages.

An AngularJS module has two parts to it:

  • A module can define its own controllers, services, factories, and directives. These are functions and code that can be accessed throughout the module.
  • The module can also depend on other modules as dependencies, which are defined when the module is instantiated. What this means is that AngularJS will go and find the module with that particular name, and ensure that any functions, controllers, services, etc. defined in that module are made available to all the code defined in this module.

In addition to being a container for related JavaScript, the module is also what AngularJS uses to bootstrap ...

Get AngularJS: Up and Running now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.