为Angular JS应用程序制作10秒定时器 [英] Making a 10 second timer for an Angular JS application

查看:153
本文介绍了为Angular JS应用程序制作10秒定时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Angular JS的测验应用程序,更像是提问应用程序,您可以在其中进行由问题构成的定时测验,每个问题都会给您10秒钟的回答。我已经完成了一个测验应用程序,它允许我回答问题并在最后给出结果,但我被困在如何为每个问题引入计时器的问题上?我是否必须制定单独的指令或控制器?问题是定时器需要一个$ timeout函数,它会产生一个延迟,但会在我的应用程序中造成延迟。任何帮助?



注意:我是Angular JS的初学者。



app.js:

  var app = angular.module('TheQuiz',[]); 
$ b app.controller('QuizControl',['$ scope','$ http','$ sce','$ timeout',function($ scope,$ http,$ sce,$ timeout ){

$ scope.score = 0;
$ scope.presentQues = -1;
$ scope.presentQuesAnswered = 0;
$ scope.percent = 0 ;
$ scope.playername = $ scope.playername;
$ scope.myself = false;

$ http.get('getdata.php')。then(function( qData){
$ scope.Questions = qData.data;
$ scope.fullQuestions = $ scope.Questions.length;
});

$ scope。 startQuiz = function(){
if($ scope.playername.length){
$ scope.presentQues = 0;
}
}

$ scope.restart = function(){

$ scope.score = 0;
$ scope.presentQues = -1;
$ scope.presentQuesAnswered = 0;
$ scope.percent = 0;
$ scope.playername =;
$ http.get('getdata.php')。then(function(qData){
$ scope.Questions = qData.data;
$ scope.fullQuestions = $ scope.Questions.length;

});



$ scope.selectAns = function(pIndex,rIndex){

var quesState = $ scope.Questions [pIndex] .quesState;

if(quesState!='answers'){

$ scope.Questions [pIndex] .selectedAns = rIndex;
var rightAns = $ scope.Questions [pIndex] .correct;
$ scope.Questions [pIndex] .rightAns = rightAns;

if(rIndex === rightAns){
$ scope.Questions [pIndex] .correctness ='correct';
$ scope.score + = 1;
}

else {
$ scope.Questions [pIndex] .correctness ='incorrect';
}

$ scope.Questions [pIndex] .quesState =回答;

$ b $ scope.percentage =(($ scope.score / $ scope.fullQuestions)* 100).toFixed(2);


$ b $ scope.yesselected = function(pIndex,rIndex){
return $ scope.Questions [pIndex] .selectedAns === rIndex;
}

$ scope.yescorrect = function(pIndex,rIndex){
return $ scope.Questions [pIndex] .rightAns === rIndex;

$ b $ scope.Continue = function(){
return $ scope.presentQues + = 1;
}

$ scope.Pass = function(){
return $ scope.presentQues + = 1;
}

}]);


解决方案

使用 moment.js 库。它使生活变得更加简单。



我使用Angular 1.5.x构建了这个,并使用了一个组件。



下面是工作版本的链接。为了便于使用,我在组件上添加了一些属性,但是如果需要的话,这些属性可以隐藏起来。

。只需设置金额和单位。即10小时倒计时,只需将cmp-from设置为10并将cmp-unit设置为小时即可。这些值在时刻模仿 format()方法( )库使用 add()方法。



我还添加了一个onEnd方法,以便任何父控制器可以通知计时器结束。



这完全是为了演示的目的,理想情况下这应该遵循更多的功能编程方法进行制作。

用法:

 < cmp-timer 
cmp-from =10
cmp-unit =second
cmp-on-end = $ ctrl.doSomething()>
< / cmp-timer>

组件:

 < code $> $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $'$'$'$'$'$'$'$'$'$' 
cmpUnit:'@',
cmpOnEnd:'&'
},
模板:'< div class =timer> {{$ ctrl.timeRemaining} }< / div>',
controller:function($ interval){
var vm = this,ONE_SECOND = 1000,timerInterval;

startTimer(){
var END_TIME = vm.getEndTime();

函数update(){
vm.timeRemaining = moment((moment(END_TIME) - moment()))。format(HH (mm):mm:ss);
}

timerInterval = $ interval(function(){
if(moment()> moment(END_TIME))return vm.stopTimer );

update();
},ONE_SECOND);

update();
}

vm。 getEndTime = function(){
return moment()。add(vm.cmpFrom,vm.cmpUnit);


vm.stopTimer = function(){
alert('Time \\''s up!');

vm.cmpOnEnd();

vm。$ onDestroy();
}

vm。$ onDestroy = function(){
$ interval.cancel(timerInterval);
}

vm。$ onInit = startTimer;
}
});

我推荐的方法是使用外部控制器/视图并使用 ngIf 在您准备好时显示或隐藏cmp-timer。


I was working on a quiz application in Angular JS, more like the quiz up application where you can have a timed quiz consisting of questions, each question giving you 10 seconds to answer.I have completed making a quiz application which allows me to answer questions and at the end giving results but i am stuck on the problem of how I can introduce a timer for each of my questions? Do i have to make a separate directive or a controller? The problem is that the timer requires a $timeout function which creates a delay but that creates a delay in my application altogether. Any help?

Note : I am a beginner in Angular JS.

app.js :

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

app.controller('QuizControl',['$scope','$http','$sce','$timeout',function($scope,$http,$sce,$timeout){

    $scope.score = 0;
    $scope.presentQues = -1;
    $scope.presentQuesAnswered = 0;
    $scope.percent = 0;
    $scope.playername = $scope.playername;
    $scope.myself = false;

    $http.get('getdata.php').then(function(qData){
        $scope.Questions = qData.data;
        $scope.fullQuestions = $scope.Questions.length;
    });

    $scope.startQuiz = function(){
        if ($scope.playername.length){
            $scope.presentQues = 0;
        }
    }

    $scope.restart = function(){

        $scope.score = 0;
        $scope.presentQues = -1;
        $scope.presentQuesAnswered = 0;
        $scope.percent = 0;
        $scope.playername = "";
        $http.get('getdata.php').then(function(qData){
        $scope.Questions = qData.data;
        $scope.fullQuestions = $scope.Questions.length;

    });

    }

    $scope.selectAns = function(pIndex , rIndex){

        var quesState = $scope.Questions[pIndex].quesState;

        if ( quesState != 'answered' ){

            $scope.Questions[pIndex].selectedAns = rIndex;
            var rightAns = $scope.Questions[pIndex].correct;
            $scope.Questions[pIndex].rightAns = rightAns;

            if (rIndex === rightAns){
                 $scope.Questions[pIndex].correctness = 'correct';
                $scope.score += 1;
            }

            else {
                $scope.Questions[pIndex].correctness = 'incorrect';
            }

            $scope.Questions[pIndex].quesState = "answered";
        }

        $scope.percentage = (($scope.score / $scope.fullQuestions) * 100).toFixed(2);

    }

    $scope.yesselected = function(pIndex , rIndex){
        return  $scope.Questions[pIndex].selectedAns === rIndex;
    }

    $scope.yescorrect = function(pIndex , rIndex){
        return  $scope.Questions[pIndex].rightAns === rIndex;
    }

    $scope.Continue = function(){
        return $scope.presentQues += 1;
    }

    $scope.Pass = function(){
          return $scope.presentQues += 1;
    }

}]);

解决方案

Your best bet when working with time in Javascript is to use the moment.js library. It makes life a lot easier.

I've built this using Angular 1.5.x and used a component.

Here's a link to a working version.

I've added a couple of properties on the component for ease of use but of course this can be hidden from users if needed. Simply set the amount and the unit. i.e for 10 hour countdown, simply set cmp-from to 10 and cmp-unit to hour. These values mimic the format() method in the moment() library using the add() method.

I've also added an onEnd method so that any parent controller can be notified of the timer ending.

This is purely for demoing purposes only, ideally this should follow a more functional programming approach for production.

Usage:

<cmp-timer
  cmp-from="10"
  cmp-unit="second"
  cmp-on-end="$ctrl.doSomething()">
</cmp-timer>

Component:

angular
  .module('app', [])
  .component('cmpTimer', {
    bindings: {
      cmpFrom: '<',
      cmpUnit: '@',
      cmpOnEnd: '&'
    },
    template: '<div class="timer">{{$ctrl.timeRemaining}}</div>',
    controller: function ($interval) {
      var vm = this, ONE_SECOND = 1000, timerInterval;

      function startTimer() {
        var END_TIME = vm.getEndTime();

        function update() {     
          vm.timeRemaining = moment((moment(END_TIME) - moment())).format("HH:mm:ss");
        }

        timerInterval = $interval(function() {
          if (moment() > moment(END_TIME)) return vm.stopTimer();

          update();
        }, ONE_SECOND);

        update();
      }

      vm.getEndTime = function() {
        return moment().add(vm.cmpFrom, vm.cmpUnit);
      }

      vm.stopTimer = function() {
        alert('Time\'s up!');

        vm.cmpOnEnd();

        vm.$onDestroy();
      }

      vm.$onDestroy = function() {
        $interval.cancel(timerInterval);
      }

      vm.$onInit = startTimer;
    }
  });

The approach I would recommend would be to have an outer controller/view and use ngIf to show or hide the cmp-timer whenever your ready to do so.

这篇关于为Angular JS应用程序制作10秒定时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆