Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用AngularJS和HTML制作滴答作响的时钟(时间)_Html_Angularjs_Time_Clock - Fatal编程技术网

如何用AngularJS和HTML制作滴答作响的时钟(时间)

如何用AngularJS和HTML制作滴答作响的时钟(时间),html,angularjs,time,clock,Html,Angularjs,Time,Clock,我是一个初学者AngularJS/html用户,一直试图找到一个代码片段来为web应用程序制作时钟/时间项 网络搜索并没有像我期望的那样简单地提供直接的结果,所以我想我会发布这个问题来获得一些答案,同时也让其他人更容易找到 我已经发布了我的解决方案,但在选择答案之前,我想看看是否有更好的解决方案 这对我来说非常好用,我认为对noobs来说很容易遵循。看到它在行动吗 JavaScript: function TimeCtrl($scope, $timeout) { $scope.clock

我是一个初学者AngularJS/html用户,一直试图找到一个代码片段来为web应用程序制作时钟/时间项

网络搜索并没有像我期望的那样简单地提供直接的结果,所以我想我会发布这个问题来获得一些答案,同时也让其他人更容易找到


我已经发布了我的解决方案,但在选择答案之前,我想看看是否有更好的解决方案

这对我来说非常好用,我认为对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);
}
<div ng-controller='TimeCtrl'>
    <p>{{ clock  | date:'medium'}}</p>
</div>
<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:

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);
}
<div ng-controller='TimeCtrl'>
    <p>{{ clock  | date:'medium'}}</p>
</div>
<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>

{{时钟|日期:'medium'}

不要忘记将angularJS和“ng应用程序”包含在您的body标签中。

有一个关于如何使用Angular文档中的间隔来实现此目的的示例。您也可以在plunker中试用

代码如下:

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);
}
<div ng-controller='TimeCtrl'>
    <p>{{ clock  | date:'medium'}}</p>
</div>
<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>

angular.module('intervalExample',[])
.controller('ExampleController',['$scope','$interval',',
函数($scope,$interval){
$scope.format='M/d/yy h:mm:ss a';
$scope.blood_1=100;
$scope.blood_2=120;
var停止;
$scope.fight=函数(){
//如果我们已经在战斗,就不要开始新的战斗
如果(角度定义(停止))返回;
stop=$interval(函数(){
如果($scope.blood_1>0&&$scope.blood_2>0){
$scope.blood_1=$scope.blood_1-3;
$scope.blood_2=$scope.blood_2-4;
}否则{
$scope.stopfait();
}
}, 100);
};
$scope.stopfait=函数(){
如果(角度已定义(停止)){
$interval.cancel(停止);
停止=未定义;
}
};
$scope.resetFight=函数(){
$scope.blood_1=100;
$scope.blood_2=120;
};
$scope.$on(“$destroy”,函数(){
//确保间隔也被破坏
$scope.stopfait();
});
}])
//注册“myCurrentTime”指令工厂方法。
//我们注入了$interval和dateFilter服务,因为工厂方法是DI。
.directive('myCurrentTime',['$interval','dateFilter',
函数($interval,dateFilter){
//返回指令链接函数。(不需要编译函数)
返回函数(范围、元素、属性){
var格式,//日期格式
stopTime;//以便我们可以取消时间更新
//用于更新用户界面
函数updateTime(){
text(dateFilter(newdate(),format));
}
//观察表达式,并在更改时更新UI。
范围$watch(attrs.myCurrentTime,函数(值){
格式=值;
updateTime();
});
stopTime=$interval(updateTime,1000);
//侦听DOM销毁(删除)事件,并取消下一次UI更新
//以防止删除DOM元素后的更新时间。
在(“$destroy”,function()上{
$interval.cancel(停止时间);
});
}
}]);
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>
<div ng-controller='TimeCtrl as timeCtrl'>
    <p>{{ timeCtrl.clock.time | date:'medium'}}</p>
</div>
<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:{{Blood_1}} 血液2:{{Blood_2}} 搏斗 停战 重新战斗
结果如下:
只是想改进Armen的答案。您可以使用
$interval
服务设置计时器

var module=angular.module('myApp',[]);
模块控制器('TimeCtrl',函数($scope,$interval){
var tick=函数(){
$scope.clock=Date.now();
}
勾选();
$interval(滴答1000);
});

{{时钟|日期:'HH:mm:ss'}


这是我用以下方法得出的最简单的答案:

JS

function TimeCtrl($interval) {
     var timeController = this;

     timeController.clock = { time: "", interval: 1000 };

     $interval(function () { 
         timeController.clock.time = Date.now();}, 
         timeController.clock.interval);
}
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>
  <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>
<div ng-controller='TimeCtrl as timeCtrl'>
    <p>{{ timeCtrl.clock.time | date:'medium'}}</p>
</div>
<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>
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>
<div ng-controller='TimeCtrl as timeCtrl'>
    <p>{{ timeCtrl.clock.time | date:'medium'}}</p>
</div>
<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>

日期:{timeCtrl.clock.time |日期:'medium'}

计时器:{timeCtrl.Timer.time |日期:'mm:ss:sss'}

开始 重置 停止
您可以使用此代码。它更简单


时钟应用程序
当前时间为:{{timeString}}

变量模块=角度模块(“clockApp”,[]); 模块控制器(“MainCtrl”,TimeCtrl); 函数TimeCtrl($scope){ var currentDate=新日期(); $scope.timeString=currentDate.toTimeString(); }
我创建了一个小指令来显示数字时钟。需要自调用函数,因为在呈现时钟时会有一秒钟的延迟

var-app=angular.module('clock',[]);
应用程序指令(“数字时钟”,函数($timeout,dateFilter){
返回{
限制:'E',
链接:功能(范围、要素){
(函数updatelock(){
text(dateFilter(newdate(),'H:mm:ss');
$timeout(updatelock,1000);
})();
}
};
});

数字钟
数字钟

最好的方法是使用可观察的时间间隔:

this.now = interval(1000).pipe(timestamp(), map(t => new Date(t.timestamp)));
然后使用async和date管道显示数据:

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

使用$interval可以更优雅地实现这一点;为什么要使用scope而不是click var time=this;?您还应该使用一个指令来实现这一点,并能够执行如下操作:
发现本页充满了示例-应该会有所帮助。我同意安德烈的观点,
$scope.clock=Date.now()$间隔(函数(){$scope.clock=Date.now();},1000)此代码不会更新时钟,因此不适用于“滴答”时钟