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="" rel="stylesheet">
  2. <script src=""></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', []);
  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