programing

Angular에서 똑딱거리는 시계(시간) 만드는 방법JS 및 HTML

jooyons 2023. 3. 11. 08:52
반응형

Angular에서 똑딱거리는 시계(시간) 만드는 방법JS 및 HTML

나는 초보자 앵글웹 앱의 시계/시간 항목을 만들기 위한 코드 스니펫을 찾고 있는 JS/html 사용자.

웹 검색은 제가 기대했던 것만큼 간단한 결과를 쉽게 얻을 수 없었기 때문에, 저는 이 질문을 올려서 답을 얻고 다른 사람들이 쉽게 찾을 수 있도록 하려고 생각했습니다.

솔루션을 게시했지만 답을 선택하기 전에 더 나은 솔루션이 있는지 알고 싶습니다.

단지 아르메니아인의 대답을 개선하려고 했을 뿐이야.를 사용할 수 있습니다.$intervalservice를 사용하여 타이머를 설정합니다.

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

module.controller('TimeCtrl', function($scope, $interval) {
  var tick = function() {
    $scope.clock = Date.now();
  }
  tick();
  $interval(tick, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.min.js"></script>

<div ng-app="myApp">
  <div ng-controller='TimeCtrl'>
    <p>{{ clock | date:'HH:mm:ss'}}</p>
  </div>
</div>

이것은 나에게 꽤 잘 작동하며 나는 noobs에 따라하기 쉽다고 생각한다.실제 동작은 이쪽에서 확인

JavaScript:

function TimeCtrl($scope, $timeout) {
    $scope.clock = "loading clock..."; // initialise the time variable
    $scope.tickInterval = 1000 //ms

    var tick = function() {
        $scope.clock = Date.now() // get the current time
        $timeout(tick, $scope.tickInterval); // reset the timer
    }

    // Start the timer
    $timeout(tick, $scope.tickInterval);
}

HTML:

<div ng-controller='TimeCtrl'>
    <p>{{ clock  | date:'medium'}}</p>
</div>

각진 것을 포함시키는 것을 잊지 마세요.JS와 바디태그에 있는 'ng-app'입니다.

이것이 $interval을 사용하여 생각할 수 있는 가장 간단한 답변입니다.

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>

다음은 동일한 $interval 등록 함수를 사용하여 시작 시 새 간격을 등록하고 중지 시 간격을 취소하는 타이머 구현입니다.

경고! $interval 지연 매개 변수에 바인딩할 수 없습니다.

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>

디지털 시계를 표시하기 위한 작은 지시문을 만들었습니다.클럭 렌더링 시 1초의 지연이 발생하기 때문에 셀프 호출 기능이 필요합니다.

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

app.directive("digitalClock", function($timeout, dateFilter) {
  return {
    restrict: 'E',
    link: function(scope, iElement) {
      (function updateClock() {
        iElement.text(dateFilter(new Date(), 'H:mm:ss'));
        $timeout(updateClock, 1000);
      })();
    }
  };
});
<!DOCTYPE html>
<html ng-app="clock">

<head>
  <meta charset="utf-8" />
  <title>Digital clock</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>

<body>
  <h1 class="text-center">Digital Clock</h1>
<digital-clock></digital-clock>
</body>

</html>

Angular docs에서 간격을 사용하여 이를 달성하는 예를 보여 줍니다.플런커로 입어보실 수도 있습니다.

코드는 다음과 같습니다.

Javascript:

<script>
  angular.module('intervalExample', [])
    .controller('ExampleController', ['$scope', '$interval',
      function($scope, $interval) {
        $scope.format = 'M/d/yy h:mm:ss a';
        $scope.blood_1 = 100;
        $scope.blood_2 = 120;

        var stop;
        $scope.fight = function() {
          // Don't start a new fight if we are already fighting
          if ( angular.isDefined(stop) ) return;

          stop = $interval(function() {
            if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
              $scope.blood_1 = $scope.blood_1 - 3;
              $scope.blood_2 = $scope.blood_2 - 4;
            } else {
              $scope.stopFight();
            }
          }, 100);
        };

        $scope.stopFight = function() {
          if (angular.isDefined(stop)) {
            $interval.cancel(stop);
            stop = undefined;
          }
        };

        $scope.resetFight = function() {
          $scope.blood_1 = 100;
          $scope.blood_2 = 120;
        };

        $scope.$on('$destroy', function() {
          // Make sure that the interval is destroyed too
          $scope.stopFight();
        });
      }])
    // Register the 'myCurrentTime' directive factory method.
    // We inject $interval and dateFilter service since the factory method is DI.
    .directive('myCurrentTime', ['$interval', 'dateFilter',
      function($interval, dateFilter) {
        // return the directive link function. (compile function not needed)
        return function(scope, element, attrs) {
          var format,  // date format
              stopTime; // so that we can cancel the time updates

          // used to update the UI
          function updateTime() {
            element.text(dateFilter(new Date(), format));
          }

          // watch the expression, and update the UI on change.
          scope.$watch(attrs.myCurrentTime, function(value) {
            format = value;
            updateTime();
          });

          stopTime = $interval(updateTime, 1000);

          // listen on DOM destroy (removal) event, and cancel the next UI update
          // to prevent updating time after the DOM element was removed.
          element.on('$destroy', function() {
            $interval.cancel(stopTime);
          });
        }
      }]);
</script>

HTML

<div>
  <div ng-controller="ExampleController">
    <label>Date format: <input ng-model="format"></label> <hr/>
    Current time is: <span my-current-time="format"></span>
    <hr/>
    Blood 1 : <font color='red'>{{blood_1}}</font>
    Blood 2 : <font color='red'>{{blood_2}}</font>
    <button type="button" data-ng-click="fight()">Fight</button>
    <button type="button" data-ng-click="stopFight()">StopFight</button>
    <button type="button" data-ng-click="resetFight()">resetFight</button>
  </div>
</div>

결과는 다음과 같습니다.여기에 이미지 설명 입력

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval) {
    $scope.theTime = new Date().toLocaleTimeString();
    $interval(function () {
        $scope.theTime = new Date().toLocaleTimeString();
    }, 1000);
});

이 코드를 사용할 수 있습니다.그게 더 간단해.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="clockApp">
    <head>
        <script src="../angular.js"></script>
    </head>
    <body>
        <h1> Clock App </h1>
        <div ng-controller="MainCtrl">
            <p> The current time is : {{timeString}}</p>
        </div>

        <script>
          var module = angular.module("clockApp", []);
          module.controller("MainCtrl", TimeCtrl);     

                    function TimeCtrl($scope){
                         var currentDate = new Date();
                        $scope.timeString = currentDate.toTimeString();                        
                    }
       </script>
    </body>
</html>

이를 위한 가장 좋은 방법은 관측 가능한 구간을 사용하는 것입니다.

this.now = interval(1000).pipe(timestamp(), map(t => new Date(t.timestamp)));

그런 다음 비동기 파이프와 날짜 파이프를 사용하여 데이터를 표시합니다.

Now: {{ this.now | async | date: 'mediumTime' }}

언급URL : https://stackoverflow.com/questions/23383233/how-to-make-a-ticking-clock-time-in-angularjs-and-html

반응형