27.03.2017 Views

ng-book

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Architecture 384<br />

<br />

With our view variable safely tucked away in the directive, we no lo<strong>ng</strong>er need to hold onto the view<br />

conditional in our controller. It’s a best practice to keep our controllers thin; usi<strong>ng</strong> directives allows<br />

us to do so efficiently.<br />

Additionally, isolati<strong>ng</strong> our login routes inside of a directive, as above, also makes it very easy to test<br />

their functionality.<br />

Shari<strong>ng</strong> Data between Controllers<br />

In A<strong>ng</strong>ular, we can share data between two controllers in a few different ways. We can nest our<br />

controllers underneath the same parent controller and allow each controller to independently modify<br />

the values of the parent controller’s $scope attribute, or we can share a value inside of a service.<br />

It’s preferable to hold onto data inside of a service, but the more efficient method can depend upon<br />

the situation. For instance, inside of a dialog box, it makes sense for us to hold onto the data that the<br />

dialog box is showi<strong>ng</strong> inside of a parent controller.<br />

Directives<br />

Knowi<strong>ng</strong> when to write a directive is as important as to knowi<strong>ng</strong> when not to write one. More often<br />

than not, it’s generally a good idea to write a directive.<br />

It’s always better to err on the side of usi<strong>ng</strong> directives over not usi<strong>ng</strong> directives. As we’ve seen above,<br />

they reduce the amount of clutter inside of our controller.<br />

It’s also much simpler to test directives than to test controllers.<br />

Directives do not always need to have a view template. Oftentimes, they can simply serve as a shim<br />

to handle deali<strong>ng</strong> with data underneath the view. The <strong>ng</strong>ModelController is an example of when<br />

this functionality comes in handy.<br />

Testi<strong>ng</strong><br />

We always encourage testi<strong>ng</strong> inside of our apps. We constantly strive to write unit tests for any<br />

piece of functionality that has any level of complexity. These tests allow us to feel confident about<br />

our code, no matter how small. Focusi<strong>ng</strong> on unit tests also enables us to be efficient with time and<br />

to focus on functionality.<br />

Once we’re confident we have tested the API of our A<strong>ng</strong>ular apps with unit tests, we can start to<br />

write end-to-end tests. End-to-end tests can be brittle and dependent upon the view, so we usually

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

Saved successfully!

Ooh no, something went wrong!