How to get current time from Angular Timer

2019-07-06 18:08发布

问题:

I am testing the Angular Timer and have found myself wondering about how to get the current time inside my controller in order to use it to whatever purpose I might have.

For instance, I want to set the font color of the timer to red when it reaches a specifict amount of minutes, but I was completely unable to do this.

I tried the following:

$scope.startTimer = function (deadline) {
    $scope.$broadcast('timer-start');
    $scope.timerRunning = true;
    if ($scope.minutes == deadline)
        $scope.turnRed();
};

This is the complete code: jsFiddle.

I also tried separatedly to just change the color in some other event calling the turnRed() function and for some weird reason it didn't work either.

I am sorry in advance that I wasn't able to add the angular timer library to the fiddle cause I am really new to it... If you could also help with this point I would really appreciate it!

回答1:

You can use timer-tick event here

$scope.$on('timer-tick', function (event, data) {
    if ($scope.timerRunning === true && data.millis >= $scope.deadlineInMilli) {
        $scope.$apply($scope.turnRed);
    }
});

And you need to convert your minutes to milliseconds for comparison

$scope.startTimer = function (deadline) {
    ....
    $scope.deadlineInMilli = +deadline * 1000 * 60; // converting to milliseconds
};

See the DEMO