AngularJS controller basic clock example

Angularjs basic controller clock example to display date and update it every second. We’ll use controller, template and $timeout.

<div ng-app="myApp" ng-controller='MyCtrl'>
  <p>date: {{dateVal}}</p>
</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script>
var module = angular.module('myApp', []);
module.controller('MyCtrl', function($scope, $timeout) {
  $scope.dateVal = new Date();
  var update = function() {
    $scope.dateVal = new Date();
    $timeout(update, 1000);
  }
  $timeout(update, 1000);
});
</script>
refresh

We used AngularJS $timeout here. If we use Javascript setTimeout, then $scope.$apply() have to be called explicitly after updating dateVal

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments