Simple directive and service demo
Externalize the time into a separate directive component.
by Rishi Kumar
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
<div ng-app='demo'>
<h3>Greeting</h3>
<p ng-controller='MyCtrl'>Hi, it's {{name}}.
The current time is <display-time />.</p>
</div>
JavaScript
var demo = angular.module('demo', []);
demo.controller("MyCtrl",function MyCtrl ($scope) {
$scope.name = 'Ken';
$scope.myTime = new Date(); // now
})
demo.factory("timerService",function(){
return function(){
var currentDate = new Date();
return currentDate.toTimeString();
}
})
demo.directive('displayTime', function($parse,$interval,timerService) {
return {
restrict: 'E',
replace: true,
transclude: false,
template: '<span class="currentTime"></span>',
controller: function($scope,$element){
this.changeTime = function(){
return timerService()
}
},
link: function (scope, element, attrs, controller) {
$interval(function(){
element.text(controller.changeTime());
},1000)
}
}});