AngularJS Directives: Using HTML5 Web Speech


Posted on October 30, 2013 by & filed under Content – Highlights and Reviews, Programming & Development.

A guest post by Jonnie Spratley, who currently works for GE as a UI Developer on the Industrial Internet Team building user interfaces for next generation products, and teaches a variety of programming courses at AcademyX.

AngularJS is one of the hottest JavaScript frameworks on the Internet, providing a full stack for creating single page applications (SPAs).

Angular Directives are a way to teach HTML new tricks. During DOM compilation, directives are matched against the HTML and executed. This allows directives to register behavior, or transform the DOM.

The Web Speech API provides an alternative input method for web applications (without using a keyboard). Developers can give web applications the ability to transcribe voice to text, from the computer’s microphone.

1ng-webspeech-bannerFollow along to see how to implement all three!

Let’s Get Started

To quickly get started creating a custom component for AngularJS, install the AngularJS Component Generator, by executing the following command:

Now you’ll be able to scaffold a angular component project.

Step 1 – Create the project

Proceed to create the project folder and then cd into that directory.

Now use Yeoman to create the project files, by executing the following command:

Then proceed to answer a few questions about your project.

For distribution, register the new project with Bower (a web library package manager), by executing the following command:

Now the component is available to the world via the bower package manager.

Step 2 – Create the Directive

To create a directive with AngularJS, it is best to create a module for the directive, then attach the directive definition to your module instance.

This allows users of the component to easily include the required scripts and declare the component in the existing application’s dependencies array.

2.1 – Module Definition

To define the module, use the angular.module() method to create a module instance; in this case the variable _app is the components module.

The angular.module is a global method for creating, registering and retrieving Angular modules.

    1. When passed two or more arguments, a new module is created.
    1. If passed only one argument, an existing module (the name passed as the first argument to module) is retrieved.

All modules that should be available to an application must be registered using this method.

2.2 – Factory Definition

The factory module is a good way to store methods or properties that can be reused throughout your directive. We create a factory for storing the icons, messages and some utility methods that the directive will use.

To register a service factory, which will be called to return the service instance, use the following format:

2.3 – Directive Definition

The directive definition object options available are as follows:

Property Description
restrict Declare how directive can be used in a template as an element, attribute, class, comment, or any combination.
priority Set the order of execution in the template relative to other directives on the element.
template Specify an inline template as a string. Not used if you’re specifying your template as a URL.
templateUrl Specify the template to be loaded by URL. This is not used if you’ve specified an inline template as a string.
replace If true, replace the current element. If false or unspecified, append this directive to the current element.
transclude Lets you move the original children of a directive to a location inside the new template.
scope Create a new scope for this directive rather than inheriting the parent scope.
controller Create a controller that publishes an API for communicating across directives.
require Require that another directive be present for this directive to function correctly.
link Programmatically modify resulting DOM element instances, add event listeners, and set up data binding.
compile Programmatically modify the DOM template for features across copies of a directive, as when used in ng-repeat.

The definition object that this directive will use is shown as follows:

2.4 – Directive Logic

Directives that modify the DOM use the link option, which takes a function with the following signature:

Parameter descriptions:

scope – is an Angular scope object.
element – is the jqLite-wrapped element that this directive matches.
attrs – is an object with the normalized attribute names and their corresponding values.
ngModel – is a ngModelController object that provides an API for the ng-model directive, with services for data-binding, validation, CSS updates, and value formatting and parsing.

a. Link Function

In order to properly hook into the directive to attach event listeners and manipulate the DOM, provide a link function.

b. Setup default options

Setup the user interface with default options.

c. Watch the Model

To watch the model for any changes call the $watch method on the scope.

d. Safe $apply

A utility for doing a safe $apply, basically this method checks to see if an $apply is already in progress.

e. Set the message

This is a utility method for setting the message value in the UI.

f. Set the icon

This is a utility method for setting the image icon in the UI.

g. Initialize

Now handle checking to see if the browser has the API.

h. Show Upgrade UI

Handle changing the UI by setting the message and the icon.

i. Start Handler

Next, handle when the recording starts up.

j. Error Handler

Handle any errors from the Speech Recognition API.

k. Result Handler

Now, handle processing the results from the Speech Recognition API.

l. Reset Handler

Handle reseting the UI after recognition is complete.

m. Toggle Button UI

Allow the user to toggle starting and stopping the recognition.

n. Start the directive

Finally, start the initialization of the directive.

2.5 – Extending

Now that we have the basic structure and logic to get the Web Speech Recognition API working with a custom UI, extending this directive to add additional functionality should be pretty seamless.

The code is available on Github, so feel free to contribute more customizable options, keyword event maps and other logic to make this directive more effective and efficient.


Download the production version or the development version.

Or install via bower:

Add to main page:

Add to main script:

Add to view:

Add to controller:


For an example visit the Plunkr.

2webspeech-tonightBe sure to look at the AngularJS resources that you can find in Safari Books Online.

Not a subscriber? Sign up for a free trial.

Safari Books Online has the content you need

Developing an AngularJS Edge is intended for intermediate JavaScript programmers. No attempt has been made to explain the JavaScript syntax used (except in the cases where AngularJS may introduce a peculiarity), nor do we explain concepts such as closures, function chaining, callbacks, or other common patterns. What we do explain are basic AngularJS concepts, components, and their applications. We provide examples along the way, answer questions, and correct common misconceptions. Together, we’ll build a working single-page weblog application using AngularJS, which will help you become proficient with using AngularJS to go out and create your own applications.
Develop smaller, lighter web apps that are simple to create and easy to test, extend, and maintain as they grow. AngularJS is a hands-on guide that introduces you to AngularJS, the open source JavaScript framework that uses Model–view–controller (MVC) architecture, data binding, client-side templates, and dependency injection to create a much-needed structure for building web applications.
Instant AngularJS Starter is designed to get you ramped up on AngularJS as quickly and efficiently as possible. By the end of this book, you’ll possess all of the knowledge you need to make full-featured, real-life applications with AngularJS. The code samples are reusable, and specifically intended to give you a head start on your next project. This book will transform your curiosity about AngularJS into a set of production-ready AngularJS skills, through a broad overview of the framework and deep dives into its key features.

About the author

jonnie Jonnie Spratley is currently working for GE as a UI Developer on the Industrial Internet Team building user interfaces for next generation products. He also teaches a variety of programming courses at AcademyX, and can be reached at @jonniespratley.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s