AngularJS Digital Clock using a Directive

Add Angular JS

First in our html, we add our Angular JS and in this tutorial, I've used CDN so you need internet connection for it to work.
  1. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  2.  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
You can place the script either in your html tag or at the bottom of body tag.

Creating our HTML

Next step is to create the place where we show our digital clock.
  1. <div class="row">
  2.         <div class="col-sm-4 col-sm-offset-4 text-center">
  3.                 <h3>Time now is:</h3>
  4.                 <my-clock></my-clock>
  5.         </div>
  6. </div>
Notice the my-clock tag? That is how we show our custom directive. That means that the name of our directive is myClock.

Adding our Angular Code

Lastly, we add our angular js scripts.
  1. var myApp = angular.module('myApp', []);
  2.  
  3. myApp.directive('myClock', function($timeout, dateFilter) {
  4.   return {
  5.     restrict: 'E',
  6.     link: function(scope, elmt) {
  7.                 (function updateClock() {
  8.                         elmt.text(dateFilter(new Date(), 'hh:mm:ss a'));
  9.                         $timeout(updateClock, 1000);
  10.                 })();
  11.         }
  12.         };
  13. });
In here, we have set our clock filter as hh:mm:ss a. You can visit this link for more reference on angular date filter. That ends this tutorial. Happy Coding :)

Add new comment