AngularJS Service Example - Time

HTML

<div ng-app="timeApp">
  <div ng-controller="Ctrl2">
    Date format: <input ng-model='format'> <hr/>
    Current time is: {{timeString}}
  </div>
</div>

CSS

</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> 
<script src="http://docs.angularjs.org/angular-1.0.1.js"></script>
<style>
.ng-invalid { border: 1px solid red; }

JavaScript

function Ctrl2($scope, time) {
    $scope.format = 'hh:mm';
    time($scope);
}

angular.module('timeApp', []).factory('time', function($timeout, dateFilter) {
    return function(scope) {
        var format = scope.format, // date format
        deferId; // deferId, so that we can cancel the time updates
        // function used to update the UI

        function updateTime() {
            scope.$apply(function() {
                scope.timeString = dateFilter(new Date(), format)
            });
        }

        // watch the expression, and update the UI on change.
        scope.$watch('format', function(value) {
            console.log("Format change!");
            format = value;
            scope.timeString = dateFilter(new Date(), format);
        });

        // schedule update in one second

        function updateLater() {
            // save the deferId for canceling
            deferId = $timeout(function() {
                updateTime(); // update DOM
                updateLater(); // schedule another update
            }, 1000);
        }

        // listen on DOM destroy (removal) event, and cancel the next UI update
        // to prevent updating time ofter the DOM element was removed.
        scope.$on('$destroy', function() {
            $timeout.cancel(deferId);
        });

        updateLater(); // kick of the UI update process.
    }
});