AngularJS Directive Example (short version alternative)

by Collin Donahue-Oponski

HTML

<div ng-app="time">
  <div ng-controller="Ctrl2">
    Date format: <input ng-model="format"> <hr/>
    Current time is: <span my-current-time="format"></span>
  </div>
</div>

CSS

</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> 
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<style>
​.ng-invalid { border: 1px solid red; }​

JavaScript

function Ctrl2($scope) {
  $scope.format = 'M/d/yy h:mm:ss a';
}

function MyCurrentTime($scope, $timeout) {
    $scope.currentTime = new Date();

    function updateLater() {
        $timeout(function() {
            $scope.currentTime = new Date();
            updateLater();
        }, 1000);
    }
    updateLater();
}

angular.module('time', [])
  .directive('myCurrentTime', function() {
      return {
          controller: MyCurrentTime,
          template: '{{currentTime | date:dateFormat}}',
          scope: {
              dateFormat: '=myCurrentTime'
          }
      };
  });