The stopwatch is a full-fledged example of how to build an angularjs directive from start to finish. This Turorial will cover the correct way to break down requirements and consolidate them into actionable items. We will explain how the directive API offers different ways to accomplish similar tasks and how to best choose what options accomplish tasks in the most efficient and readable manner. We do this by writing a stopwatch and showing how to accomplish its set of requirements. The stopwatch’s definition object could be set up in different ways. We will first see how to create the stopwatch in its most simple form and then add optimization techniques that make the stopwatch more advanced.


Stopwatch's filter

Breaking down the stopwatch

Many implementations of stopwatches are available all over the Web, which use various different techniques and styles. stopwatch is meant to be simpler and easier to implement inside of a modern web app. The directive API offers the options needed to create a sleek and straightforward piece of code that completes all the given requirements. Each of the stopwatch’s requirements can be accomplished in many ways inside of an angularjs context.

We will go over each requirement needed to build a stopwatch. When we break down each requirement, we will start to see what definition object options could be used to perform the task at hand. The major differences between the implementations that will be discussed are how to best set up a directive’s link function and when and how to use some more advanced directive API options.

Stopwatch requirements

The stopwatch has the following set of requirements that need to be fulfilled and be able to work with multiple stopwatches on the same page:

  • The ability to track its own time
  • The ability to start and stop on command
  • The ability to reset to zero on command
  • The ability to log each lap

The requirements can be accomplished in different ways. It would be common to write this directive with a link function that is full of logic that accomplishes all of these requirements. Writing directives whose link functions contain all of the implementation logic is standard and accomplishes the basic requirements; however, writing directives in this manner does not facilitate the most readable, concise code.

A simple pseudo code example of this is as follows:

  scope: true,
  link: function(scope, element, attrs){
     scope.startStop = function(){//stop or start the timer}
     scope.reset = function(){//reset the timer}
     scope.logTime = function(){//log time}