3

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!

Kutyel
  • 8,575
  • 3
  • 30
  • 61

1 Answers1

3

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

Rahil Wazir
  • 10,007
  • 11
  • 42
  • 64
  • thank you very much for your answer! It's weird cause 1h ago I opened your fiddle when my mobile and it worked fine but I am opening it right now on chrome and trying your solution in my code and it does not work :S – Kutyel Nov 16 '14 at 00:28
  • @Kutyel It would work the timer script was temporary online, use in your environment it will work fine. – Rahil Wazir Nov 16 '14 at 13:12
  • @Kutyel I have pasted the entire module to the script frame now it will work in fiddle. – Rahil Wazir Nov 16 '14 at 13:14
  • I tried your solution in my environment and the event triggers but the `h1` never gets red :/ – Kutyel Nov 16 '14 at 13:16
  • @Kutyel I can't really help without any information about your environment and how did you try. Did you try the exact same solution given in fiddle? As you can see the fiddle is almost working with what you are expecting. – Rahil Wazir Nov 16 '14 at 18:22
  • is true thx for your answer! I wil make it work ;) like the question if you want. – Kutyel Nov 16 '14 at 18:35
  • I finally found what was going on, your solution only works for AngularJS 1.2 but it's ok I will update my angular script and that will be all! :) – Kutyel Nov 17 '14 at 08:02