function timerCtrl($interval) {
var vm = this;
this.$onInit = function () {
if (!vm.startDate) vm.startDate = new Date();
renderTime();
vm.interval = $interval(function () {
renderTime();
}, 1000);
}
vm.progress = 0; //formatted elapsed time
vm.interval; //$interval
vm.startDate;
function renderTime() {
var now = new Date();
var then = vm.startDate;
var ms = moment(now).diff(moment(then));
var d = moment.duration(ms);
vm.progress = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
}
this.$onDestroy = function () {
$interval.cancel(vm.interval); //destroy interval
}
}
angular.module("as-timer", []);
angular.module("as-timer").component("timer", {
bindings: { }, //starttime as binding?
template: "{{ $ctrl.progress }}",
controller: timerCtrl
});
Component Script in Index.html integrieren
<script src="app/timer/timer.js"></script>
angular.module("app", ["as-timer"]);
Component Tag in HTML benutzen und eine Startzeit definieren:
<timer></timer>
Ersteller der Webseite MuchaDev. Selbstständiger IT Constultant für Frontend Technologien.