2

Im making function in my app that when I entered a specific number, It will display the in hh:mm:ss format and start counting down. The input number will be treated as minutes for example when I input 2, the display would be 00:02:00 then it will start counting down.

 <body ng-app="mehmetcankerApp">
 <!--counterCtrl App Controller -->   
<div ng-controller="counterCtrl">
 <!--Angular Binding -->  
 <input type="number" ng-model="counter"/>
<p ng-model="format" ng-bind="counter"  id="numOfDozens"></p>
    <button ng-click="stop()">Stop</button>
    <button ng-click="countdown()">Start</button>     
</div>

The whole code is in this plnker link: http://plnkr.co/edit/Mzv6W9smmRkaDPU4cgVa?p=preview

bleyk
  • 799
  • 3
  • 14
  • 41

2 Answers2

3

You need to use a custom filter and an interval:

var app = angular.module('app', []);

app.controller('counterCtrl', ['$scope', '$interval',

  function($scope, $interval) {
    $scope.minutes = 0;
    $scope.seconds = $scope.minutes * 60;
    $scope.$watch('minutes', function() {
      $scope.seconds = $scope.minutes * 60;
    });

    $scope.countdown = function() {
      if ($scope.seconds <= 0) return;
      $scope.countdownInterval = $interval(function() {
        if ($scope.seconds <= 0) {
          $interval.cancel(countdownInterval);
        }
        $scope.seconds--;
      }, 1000);
    };
    
    $scope.stop = function() {
       $interval.cancel($scope.countdownInterval);
    };


  }


]);

app.filter('secondsToDate', [
  function() {
    return function(seconds) {
      return new Date(1970, 0, 1).setSeconds(seconds);
    };
  }
])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="counterCtrl">
    <!--Angular Binding -->
    <input type="number" ng-model="minutes" />
    <p id="numOfDozens">{{seconds | secondsToDate | date:'HH:mm:ss'}}</p>
    <button ng-click="stop()">Stop</button>
    <button ng-click="countdown()">Start</button>
  </div>
</div>
Daniel
  • 6,194
  • 7
  • 33
  • 59
1

Working Demo

Here you can see that, I have created a function to get a sample date with exact time of the inputted text (counter).

{{getMyTime() | date: 'HH:mm:ss'}}

getMyTime() will return a sample date with correct time and formatted it with date filter.

 $scope.getMyTime = function(){
   var myTime = new Date(01,01,01);
   myTime.setMinutes($scope.counter);
   return myTime;
 }

Hope this will help you.

Please feel free to ask any doubt on this !!!

Abhilash Augustine
  • 4,128
  • 1
  • 24
  • 24