AngularJS Directive example
by michieljoris
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://docs.angularjs.org/angular-1.0.1.min.js"></script>
<style>
.ng-invalid { border: 1px solid red; }
JavaScript
function Ctrl2($scope) {
$scope.format = 'M/d/yy h:mm:ss a';
}
angular.module('time', [])
// Register the 'myCurrentTime' directive factory method.
// We inject $defer and dateFilter service since the factory method is DI.
.directive('myCurrentTime', function($timeout, dateFilter) {
// return the directive link function. (compile function not needed)
return function(scope, element, attrs) {
var format, // date format
deferId; // deferId, so that we can cancel the time updates
// used to update the UI
function updateTime() {
element.text(dateFilter(new Date(), format));
}
// watch the expression, and update the UI on change.
scope.$watch(attrs.myCurrentTime, function(value) {
format = value;
updateTime();
});
// 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.
element.bind('$destroy', function() {
$defer.cancel(deferId);
});
updateLater(); // kick of the UI update process.
}
});