Chapter 4 ■ Filters and Modules
Again, we get to provide a name ('MyFilterDemoCtrl') and pass in a function. This function is basically the same
function that we have been using as our controller within the script tags so far, only now it is attached to a module.
If controllers and other logic, such as filters, are created within an AngularJS module, how are they accessed and
used? This relates to the AngularJS bootstrapping process. Let’s examine that now.
Bootstrapping AngularJS
We talked briefly about the ngApp directive earlier in the book, though we didn’t really talk about the role it plays in
bootstrapping AngularJS. It might already have occurred to you that AngularJS is hard at work behind the scenes,
monitoring form fields, for example, so that it can respond to any changes and immediately update any bindings.
In fact, AngularJS is doing quite a lot behind the scenes, and it all starts to happen once the document is loaded,
because it found an ngApp directive. So far, we have used ngApp in its simplest form, as an attribute without any value.
However, you can specify an AngularJS default module, by providing a value. The following code snippet shows ngApp
with a value of 'myAppModule', which is the name of the module we have just created.
With the ngApp directive in place, we can save our module, myAppModule.js, into the js directory. Then we can
create a new page, index.html, which will make use of this module. The next two code listings (Listings 4-8 and
Listing 4-9) will pull all of this together.
Listing 4-8. myAppModule.js
// create a new module called 'myAppModule' and save
// a reference to it in a variable called myAppModule
var myAppModule = angular.module('myAppModule', []);
// use the myAppModule variable to
// configure the module with a controller
myAppModule.controller('MyFilterDemoCtrl', function ($scope) {
// controller code would go here
}
);
// use the myAppModule variable to
// configure the module with a filter
myAppModule.filter('stripDashes', function() {
return function(txt) {
// filter code would go here
};
});
Listing 4-8 is the module file in which we create a module and then configure a controller and a filter. Notice
that we named the JavaScript file 'myAppModule.js'; we named the variable, which stores a reference to the module
'myAppModule'; and we named the module itself 'myAppModule'. This is not an issue, and it does not always have to
be the case that naming follows this pattern. The key thing is to recognize that when we talk about the module, we
are talking about the object we created and named when we called the angular.module method. It is this name that
we can use to get a reference to the module whenever we need it. To clarify this, Listing 4-9 shows a slightly different
approach to setting up and configuring the module.