AngularJs – Timer Component

Tutorial AngularJs

von Ardian Shala, 15.02.2017 - update: 20.05.2018
Einfache AngularJs Timer Component, welche einen Zeitfortschritt mit individuellem Startzeitpunkt und Ausgabeformat mit MomentJs anzeigt.
Vorraussetzung:
  • AngularJs
  • MomentJs

Downloads:

Github Repo

Timer Component

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
});

Einbinden

Component Script in Index.html integrieren

<script src="app/timer/timer.js"></script>

Modul integrieren

angular.module("app", ["as-timer"]);

Component benutzen

Component Tag in HTML benutzen und eine Startzeit definieren:

<timer></timer>
#angularjs #timer

Autor: Ardian Shala

Ersteller der Webseite MuchaDev. Selbstständiger IT Constultant für Frontend Technologien.