Jest to najprostsza odpowiedź mogłem wymyślić użyciu $interval:
Example
JS
function TimeCtrl($interval) {
var timeController = this;
timeController.clock = { time: "", interval: 1000 };
$interval(function() {
timeController.clock.time = Date.now();},
timeController.clock.interval);
}
HTML
<div ng-controller='TimeCtrl as timeCtrl'>
<p>{{ timeCtrl.clock.time | date:'medium'}}</p>
</div>
Oto realizacja zegar stosując tę samą funkcję rejestracji $ przedział zarejestrować nowy interwał na początku i anulować interwał na przystanku.
OSTRZEŻENIE!Nie jest możliwe, by połączyć się z parametrem
Example
$ opóźnienia przedział JS
function TimeCtrl($interval) {
var timeController = this;
timeController.clock = { time: "", interval: 1000 };
timeController.timer = { time: (new Date()).setHours(0,0,0,0), startTime: "", interval: 10};
timeController.timerProcess;
timeController.timerStart = function() {
// Register the interval and hold on to the interval promise
timeController.timerProcess = RegisterInterval(TimerTick, timeController.timer.interval);
// Reset the time to 0
timeController.timerReset();
}
timeController.timerReset = function() {
timeController.timer.startTime = Date.now();
timeController.timer.time = (new Date()).setHours(0,0,0,0);
}
timeController.timerStop = function() {
// If there is an interval process then stop it
if(timeController.timerProcess){
$interval.cancel(timeController.timerProcess);
}
}
function ClockTick() {
timeController.clock.time = Date.now();
}
function TimerTick(){
// Increment the time by the time difference now and the timer start time
timeController.timer.time += Date.now() - timeController.timer.startTime;
// Reset the start time
timeController.timer.startTime = Date.now();
}
function RegisterInterval(regFunction, regInterval){
return $interval(regFunction, regInterval);
}
RegisterInterval(ClockTick, timeController.clock.interval);
}
HTML
<div ng-controller='TimeCtrl as timeCtrl'>
<p>Date: {{ timeCtrl.clock.time | date:'medium'}}</p>
<p>Timer: {{ timeCtrl.timer.time | date:'mm:ss:sss'}}</p>
<button type="button" ng-click="timeCtrl.timerStart()">Start</button>
<button type="button" ng-click="timeCtrl.timerReset()">Reset</button>
<button type="button" ng-click="timeCtrl.timerStop()">Stop</button>
</div>
Można to osiągnąć za pomocą bardziej elegancko $ interwał. –
Mam kilka pytań: Dlaczego nie zacząć od używania just tick(); i dlaczego używać zakresu, a nie coś lizać var czas = to ;? – olahell
Powinieneś także użyć dyrektywy, aby to zrobić i móc zrobić coś takiego: ' current-time>' –
OpensaurusRex