AngularJS Example
by adibih
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 ng-controller="MyTestCtrl">
<pre>Test: {{test | pick_random}}</pre>
</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.2/angular.min.js"></script>
<style>
.ng-invalid { border: 1px solid red; }
JavaScript
var myApp = angular.module('time', []);
myApp.controller('MyTestCtrl', function($scope){
$scope.test = {
numbers: [1]
};
});
myApp.filter('pick_random', function(){
return function(input){
console.log('Filter pick_random called');
return 'fixed dummy text that never changes';
};
});
myApp.controller('Ctrl2', function($scope){
$scope.format = 'M/d/yy h:mm:ss a';
});
// Register the 'myCurrentTime' directive factory method.
// We inject $timeout and dateFilter service since the factory method is DI.
myApp
.directive('myCurrentTime', function($timeout, dateFilter) {
// return the directive link function. (compile function not needed)
return {
replace: false,
transclude: true,
link: function(scope, element, attrs) {
var format, // date format
timeoutId; // timeoutId, 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 timeoutId for canceling
timeoutId = $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() {
$timeout.cancel(timeoutId);
});
updateLater(); // kick off the UI update process.
}
}
});