AngularJS Digital Clock using a Controller

Add Angular JS

First, we need to add Angular JS into our html for us to use it 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 inside your head tag or at the bottom of body tag.

Creating our Body

Next we create our body to show our clock and we also declare where we want to put our controller and ng-init function.
  1. <body ng-controller="myCtrl" ng-init="myClock()">
  2. <div class="container">
  3. <h1 class="page-header text-center">AngularJS Digital Clock using a Controller</h1>
  4. <div class="row">
  5. <div class="col-sm-4 col-sm-offset-4 text-center">
  6. <h3>Time now is:</h3>
  7. <span class="myclock">{{ clock }}</span>
  8. </div>
  9. </div>
  10. </div>
In here we have our controller named myCtrl ang we get data in our myClock function in our controller.

Adding our Angular JS script

Lastly, we add our angular script where we can find our controller and myClock function.
  1. var myApp = angular.module('myApp', []);
  3. myApp.controller('myCtrl', function($scope,$timeout,dateFilter) {
  5. $scope.myClock = function(){
  6. $timeout(function(){
  7. $scope.clock = (dateFilter(new Date(), 'hh:mm:ss a'));
  8. $scope.myClock();
  9. },1000);
  10. };
  12. });
We filter the clock in hh:mm:ss a format. If you want more reference on date filter, you can visit this link. That ends this tutorial. Happy Coding :)

Add new comment