27.03.2017 Views

ng-book

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Modules<br />

In JavaScript, placi<strong>ng</strong> functional code in the global namespace is rarely a good idea. It can cause<br />

collisions that are tough to debug and cost us precious development time.<br />

When looki<strong>ng</strong> at data bindi<strong>ng</strong> in the previous chapter, we wrote our controllers in the global<br />

namespace by defini<strong>ng</strong> a si<strong>ng</strong>le function:<br />

function MyController($scope) {<br />

var updateClock = function() {<br />

$scope.clock = new Date();<br />

};<br />

setInterval(function() {<br />

$scope.$apply(updateClock);<br />

}, 1000);<br />

updateClock();<br />

};<br />

In this chapter, we’ll talk about how to write efficient, production-ready controllers by encapsulati<strong>ng</strong><br />

our functionality in a si<strong>ng</strong>le core unit called a module.<br />

In A<strong>ng</strong>ular, a module is the main way to define an A<strong>ng</strong>ularJS app. The module of an app is where<br />

we’ll contain all of our application code. An app can contain several modules, each one containi<strong>ng</strong><br />

code that pertains to specific functionality.<br />

Usi<strong>ng</strong> modules gives us a lot of advantages, such as:<br />

• Keepi<strong>ng</strong> our global namespace clean<br />

• Maki<strong>ng</strong> tests easier to write and keepi<strong>ng</strong> them clean so as to more easily target isolated<br />

functionality<br />

• Maki<strong>ng</strong> it easy to share code between applications<br />

• Allowi<strong>ng</strong> our app to load different parts of the code in any order<br />

The A<strong>ng</strong>ular module API allows us to declare a module usi<strong>ng</strong> the a<strong>ng</strong>ular.module() API method.<br />

When declari<strong>ng</strong> a module, we need to pass two parameters to the method. The first is the name of<br />

the module we are creati<strong>ng</strong>. The second is the list of dependencies, otherwise known as injectables.<br />

a<strong>ng</strong>ular.module('myApp', []);

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!