Book Image

Mastering AngularJS Directives

By : Josh Kurz
Book Image

Mastering AngularJS Directives

By: Josh Kurz

Overview of this book

<p>AngularJS offers many features that allow the creation of rich, compelling web applications. Directives are by far the most important feature to incorporate into any skill set. This book starts off by teaching basic and advanced techniques for the art of directive writing. The different techniques are taught by a series of examples that showcase when and why certain directives should be created, based on given use cases. It moves on to explain more about how to harness the potential of AngularJS, by incorporating external libraries, optimizing code, and using brand new functions such as animations.<br /><br />Finally, the book includes an overview of the techniques and best practices that AngularJS developers need to keep in mind while developing their own applications. The overall goal of this book is to teach different aspects of directive writing that can be consumed by all levels.</p>
Table of Contents (16 chapters)
Mastering AngularJS Directives
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Free Chapter
1
The Tools of the Trade
Index

Preface

AngularJS offers a new outlook on web development that is changing more and more opinions everyday. The reason people are agreeing with AngularJS's direction is because of its orthogonal views on encapsulation and separation. Separation of logic into structurally defined realms is AngularJS's specialty, and this truth allows more focus to be placed on domain specific logic.

Directives offer the biggest form of encapsulation inside AngularJS applications. This is true because of its focus on separating the view from the model. For years, developers have combined different types of client-side logic that has no business being coupled together. The decoupling of the view and model has begun to take full effect in modern web applications, and AngularJS directives have been built with this mindset at their core.

Many say that directives are the most difficult piece of AngularJS to learn. People say this because directives take a new approach to JavaScript conventions, which has not been done before. There are not many libraries that focus on declarative approaches to handle the relationship between HTML and JavaScript. These new concepts seem difficult at first glance, but once their logic is understood, things fall into place rather quickly.

Many use cases can be solved with a simple directive or a set of directives that work in unison with each other. We will go over how to create these simple directives and how to train your mind to immediately consider them as solutions. The stages that this book goes through build on top of a singular idea. This idea is how to properly take some data model, and effectively render it and all of its changes in the view.

Once directives are understood for what they are, many great use cases can be accomplished with them. Some of the most important directives are actually built into the core itself, with the same tools available to any application. This book shows us how to use the different options made available by AngularJS to create a wide range of directives that serve many different purposes.

The differences between the directives created in this book are pretty broad. There are stopwatches, stoplights, media players, and stock charts, which can not only work together but also work individually just as well. The only central theme to each is that they are considered black belt directives and, as such, are tested and implemented just like any other production-ready software.

What this book covers

Chapter 1, The Tools of the Trade, introduces us to what a directive is, how it is created, and the different options that can be used to create them. Its main purpose is to introduce directives from a high-level perspective so that anyone can digest their meaning. To do this, the chapter is broken down into different parts that consist of basic examples showcasing the use of the different options.

Chapter 2, Building a Stopwatch Directive, introduces us to the first directive that we build in this book. The stopwatch building process goes through iterations that shed light on different design aspects. Throughout the design process, the directive is tested thoroughly to prove that its logic is correct and that any change made to it does not introduce bugs.

Each decision that went into the architecture of the directive is discussed and explained by showing the change, and then going into details about that change. The overall goal of the chapter is to create a useful directive that can be used in many different applications and to get ideas stirring about your own custom directives.

Chapter 3, Harnessing External JavaScript Libraries with Directives, discusses how many applications rely on third-party libraries to accomplish advanced DOM manipulation. These libraries can be integrated smoothly with any AngularJS application and can still abide by the concepts made by the majority in the community. The purpose of this chapter is to showcase best practices when integrating third-party libraries into AngularJS applications.

Chapter 4, Compiling the Advantages, shows you how being able to utilize AngularJS's compile cycle at will is useful in many different instances. There are few use cases that require the use of the $compile service, and these are discussed in detail. This chapter also showcases how useful it can be to generate DOM attached to AngularJS's scope in conjunction with third-party libraries and dynamic templates.

Chapter 5, Communication between Directives, shows that directives are very useful in normal circumstances. They are even more useful when they work in unison with each other to accomplish similar tasks. There are many ways to get directives to work together. Some ways include basic scope inheritance, and others include sharing portions of execution context.

This chapter takes a deep dive into the many possible ways to get directives to work with each other. No matter what their relationship, there is always a way to get two directives to work in collaboration. The examples here also help showcase how to write integration tests in order to prove the logic being used to integrate works as desired.

Chapter 6, Working with Live Data, shows that data is what makes applications important. If it were not for the data, then there would be no reason to push the Web forward. This chapter showcases the philosophies behind developing directives and their approach to working with live data.

Since the data is coming from a live source, we have kept scale in mind throughout the design of all of these examples. The scale considerations bring a large focus on different ways to write directives that deal with large amounts of data.

Chapter 7, Optimization and Code Quality, shows the importance of making sure that an application is fast and how the ability to stay agile is detrimental to its lifespan. AngularJS gives us many opportunities to write clean, fast code that does amazing things. However, with all great things comes great responsibility.

AngularJS can be used in inefficient ways that can drastically slow down a web page. This chapter showcases some things to watch out for when writing directives. Since directives are the main reason to create massive amounts of bindings, we go over how to keep the total number of bindings to a minimum. This chapter also goes over the benefits that AngularJS brings in terms of quality code and what this means for organized HTML views.

Chapter 8, Directives and Animations, shows why directives play an important role in how animations are integrated. This is because AngularJS animations have been built in a way to create another encapsulation layer that plays directly by working alongside directives. This chapter shows us how to use the animation service in core directives and how to create custom directives that use animations.

Chapter 9, Conclusion, wraps up the book with an overall summary of closing statements. There are references made to all the sections of the book, and each is given an overview. The overall goal is to finalize the ideas and concepts that have been portrayed.

What you need for this book

This book has been written to work with the 1.2.x branch. The directives that have been created will work with future versions of AngularJS, but there may be slight changes that need to occur in these future versions.

The examples that have been built are being showcased at http://angulardirectives.joshkurz.net/ and in the GitHub repo, https://github.com/joshkurz/Black-Belt-AngularJS-Directives. The instructions to install the project can be located in the README file on the GitHub repo and here.

The following are the normal requirements for today's project standards:

  • npm install -g grunt-cli http-server

  • npm install

  • bower install

  • grunt

  • *grunt protractor

All of the necessary modules are installed via npm. Grunt is used in this project to create the build file, which is tested against and used in angulardirectives.joshkurz.net. Protractor is used for all E2E tests in this book. To run Protractor tests, a web server needs be hosting the files on localhost. It is recommended to use the npm module http-server. Once you have these packages installed and all of the tests pass, you can play around with whatever you want inside the repo. Please send a PR if you would like to contribute to the project as well.

Who this book is for

If you are a developer who has previous JavaScript experience and some AngularJS experience, this is the book for you. New AngularJS users will be able to follow the concepts of this book, but there may be some references to AngularJS-specific material that is not fully defined in the book.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text, directive names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows:

"The ngInclude directive creates an opportunity to write clean organized views."

A block of code is set as follows:

$routeProvider.when('/mediaelement', {
    templateUrl:'directives/demo/mediaelement/mediaelementView.tpl.html',
    reloadOnSearch: false,
    controller:'mediaelementCtrl'
  });

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

  $routeProvider.when('/mediaelement', {
    templateUrl:'directives/demo/mediaelement/mediaelementView.tpl.html',
    reloadOnSearch: false,
    controller:'mediaelementCtrl'
  });

New terms and important words are shown in bold.

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to , and mention the book title via the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. You can also download the code from GitHub at any time by going to https://github.com/joshkurz/Black-Belt-AngularJS-Directives.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at if you are having a problem with any aspect of the book, and we will do our best to address it.