如何使用angularJS禁用或隐藏Timer

时间:2022-07-10 02:49:33

I am have displayed the Timer and Countdown Timer from 59 seconds to 0 seconds in decrease order using AngularJS. I have 2 problems,can anyone help to solve this 2 problems

我使用AngularJS以降序显示了从59秒到0秒的定时器和倒数计时器。我有2个问题,任何人都可以帮助解决这2个问题

Problem 1: But there is a problem in displaying the countdown time i.e. it is displaying the alert message before 0:1 seconds .But it should display the alert message after the count completes form 59 to 0 seconds.

问题1:但是显示倒计时时间存在问题,即它在0:1秒之前显示警报消息。但是在计数完成后,它应该在59到0秒之后显示警告消息。

code:

<!DOCTYPE html>
<html>
<head>
<meta charset="UFT-8">
<link rel="stylesheet" href="menu.css">
<link rel="stylesheet" href="layout.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script>
var pos = 0, test, test_status, question, choice, choices, chA, chB, chC, correct = 0;

var questions = [
        [ "Which of the following a is not a keyword in Java ?", "class", "interface", "extends", "C" ],

    [ "Which of the following is an interface ?", "Thread", "Date", "Calender", "A" ],

    [ "Which company released Java Version 8 ?", "Sun", "Oracle", "Adobe", "A" ],

    [ "What is the length of Java datatype int ?", "32 bit", "16 bit", "None", "C" ],

    [ "What is the default value of Java datatype boolean?","true","false","0","A"]
];
function _(x){
    return document.getElementById(x);
}

function renderQuestion(){
    test = _("test");
    if(pos >= questions.length){

        var showscore=Math.round(correct/questions.length*100);
        var minuteleft = parseInt((totalsecoriginal-totalsec) / 60, 10);
            var sec = (totalsecoriginal-totalsec) - (minuteleft * 60);

        document.getElementById("online_start").src = "animatedthankyou.gif";
        document.getElementById("showtime")

        test.innerHTML = "<h3>You got "+correct+" correct of "+questions.length+" questions</h3>";
        test.innerHTML += "<h3> Your Grade : "+showscore +"% </h3>";
        test.innerHTML += "<h4>Exam Finished in Time :" + minuteleft + " Minutes :" + sec + " Seconds</h4>";
        test.innerHTML += "<button onclick='EndExam()'>End the Exam</button>";
        _("test_status").innerHTML = "<h3>Test Completed</h3>";
        pos = 0;
        correct = 0;
                clearTimeout(tim);
        document.getElementById("starttime").style.display += 'none';
        document.getElementById("showtime").style.display += 'none';
                document.getElementById("endtime").style.display += 'none';
        return false;
    }

    _("test_status").innerHTML = "<h3>Question "+(pos+1)+" of "+questions.length+"</h3>";
    question = questions[pos][0];
    chA = questions[pos][1];
    chB = questions[pos][2];
    chC = questions[pos][3];
    test.innerHTML = "<h3>"+question+"</h3>";
    test.innerHTML += "<input type='radio' name='choices' value='A'> "+chA+"<br>";
    test.innerHTML += "<input type='radio' name='choices' value='B'> "+chB+"<br>";
    test.innerHTML += "<input type='radio' name='choices' value='C'> "+chC+"<br><br>";
    test.innerHTML += "<button onclick='checkAnswer()'>Next</button><br><br>";


}
function checkAnswer(){
    choices = document.getElementsByName("choices");
    choice=-1;
    for(var i=0; i<choices.length; i++){
        if(choices[i].checked){
            choice = choices[i].value;
        }
    }
    if(choice == questions[pos][4]){
        correct++;
    }
    pos++;
    renderQuestion();
}

window.addEventListener("load", renderQuestion, false);


function EndExam(){

location.href="Loginpage.htm";
}


    var tim;
        var showscore=Math.round(correct/questions.length*100);
        var totalsec = 60;
    var totalsecoriginal = totalsec;
        var f = new Date();


        function starttime() {
            showtime();
                var showcurtime = moment();
            var curtimeformat = showcurtime.format('h:mm:ss a');
            var showendtime = showcurtime.add(totalsec, 's');
            var endtimeFormat = showendtime.format('h:mm:ss a');

        document.getElementById("starttime").innerHTML = "<h4>Starting Time " + curtimeformat + "</h4>";

            document.getElementById("endtime").innerHTML = "<h4>Ending Time " + endtimeFormat + "</h4>";    

        }



                        //  Using Angular JS

    var app = angular.module('MyApp',[])
        app.controller('MyController',function($scope,$window,$interval,$timeout,$filter){



                var date=new Date();
        $scope.hhmmss = $filter('date')(new Date(), 'hh:mm:ss a');

        $scope.currentTime = new Date();
        $scope.currentTime .setSeconds($scope.currentTime .getSeconds() + 60);



        //CountDown TImer

        var tim;
            $scope.totalsec = 60;
            var countdowntime= function(){
        $scope.totalsec--;
        $scope.min = parseInt($scope.totalsec / 60, 10);
            $scope.sec = $scope.totalsec - ($scope.min * 60);

        if($scope.sec >0){
        tim = $timeout(countdowntime, 1000);
        }else if($scope.sec== 0){
        $timeout.cancel(tim);
        $window.alert("Time Up");
        }

        };

        countdowntime();


});

</script>

</head>

<body onload="starttime()" >

<div id="Holder">
<div id="Header"></div>
<div id="NavBar">
<nav>
<ul>
<li><a href="Loginpage.htm"> Login</a></li>
<li><a href="Registrationpage.htm">Registration</a></li>
</ul>
</div>


<div id="Content">
<div id="PageHeading">
<h1><marquee direction="right" behavior="alternate">All the Best</marquee></h1>
</div>

<div id="ContentLeft">
<h2></h2><br>
<img id="online_start">
<br>
<h6>Online Examination System(OES) is a Multiple Choice Questions(MCQ) based 
examination system that provides an easy to use environment for both 
Test Conducters and Students appearing for Examination.</h6>
</div>
 <div id="ContentRight">
<section class="loginform_cf">
<div ng-app="MyApp" ng-controller="MyController"  ng-init="StartTimer()">
<table>
    <tr>
          <td id="test_status"  style="text-align:left" ></td>


     <td>   Exam Starts :<span ng-bind = "hhmmss">  </span>   </td>
     <td>   Exam Ends : {{currentTime | date:'HH:mm:ss a'}}    </td>


    </tr>

    <tr>
    <td id="test" colspan="3"></td>
    </tr>


</table> 





<br>

Your Left Time is :{{min}} Minutes:{{sec}} Seconds<br> 


</div>



<br>


</section>
</div>

</div>


<div id="Footer">Developed by - K.P.RAJU</div>


</div>

<script src="moment.js"></script>

</body>
</html>

Problem 2:

At the end of the exam Exam Starts :10:35:39 AM and Exam Ends : 10:36:39 AM timer should disable .The page should display as shown below

考试结束时考试开始时间:10:3​​5:39 AM和考试结束时间:10:3​​6:39 AM计时器应该禁用。页面应显示如下图所示

Test Completed

You got 0 correct of 5 questions

你得到0个正确的5个问题

Your Grade : 0%

你的成绩:0%

Exam Finished in Time :0 Minutes :4 Seconds

考试时间结束:0分钟:4秒

2 个解决方案

#1


0  

To try solve your 1st problem, try putting alert inside timeout, like

要尝试解决您的第一个问题,请尝试将警报置于超时范围内,例如

  $timeout(function() {
        $window.alert("Time Up");
    },0);

Because JavaScript is single thread, AngularJS must be run in callback mode, so the alert is called before AngularJS rendering getting called.

因为JavaScript是单线程,所以AngularJS必须在回调模式下运行,因此在调用AngularJS渲染之前调用警报。

2nd, sorry didn't get you

2,抱歉没有得到你

#2


0  

I have changed your code to angular and used interval to run the time and ng-show and ng-hide directives.

我已将您的代码更改为角度并使用间隔来运行时间和ng-show和ng-hide指令。

SCRIPT and HTML

脚本和HTML

var app = angular.module('MyApp', [])
app.controller('MyController', function($scope, $compile, $window, $interval, $timeout, $filter) {

  $scope.pos = 0, $scope.correct = 0, $scope.ques = true;

  $scope.questions = [
    ["Which of the following a is not a keyword in Java ?", "class", "interface", "extends", "C"],

    ["Which of the following is an interface ?", "Thread", "Date", "Calender", "A"],

    ["Which company released Java Version 8 ?", "Sun", "Oracle", "Adobe", "A"],

    ["What is the length of Java datatype int ?", "32 bit", "16 bit", "None", "C"],

    ["What is the default value of Java datatype boolean?", "true", "false", "0", "A"]
  ];


  $scope.totalsecoriginal = $scope.totalsec = 60;
  $scope.totalsec--;
  $scope.min = parseInt($scope.totalsec / 60, 10);
  $scope.sec = $scope.totalsec - ($scope.min * 60);
  $scope.date = new Date();
  $scope.hhmmss = $filter('date')(new Date(), 'hh:mm:ss a');

  $scope.currentTime = new Date();
  $scope.currentTime.setSeconds($scope.currentTime.getSeconds() + 60);


  function _(x) {
    console.log(angular.element(document.getElementById(x)));
    return angular.element(document.getElementById(x))[0];
  }
  $scope.interval = $interval(function() {
    if ($scope.sec === 0) {
      $scope.min--;
      $scope.sec = 60;
    }
    $scope.sec--;
  }, 1000);
  $scope.$watch('sec', function() {
    if ($scope.min === 0 && $scope.sec === 0) {
      $interval.cancel($scope.interval);
      window.alert('Time Up!!!');
      $scope.pos = $scope.questions.length;
      $scope.temp = true;
      $scope.renderQuestion();
    }

  })
  $scope.renderQuestion = function() {
    if ($scope.pos >= $scope.questions.length) {
      $scope.ques = false;
      if (!$scope.temp) { $scope.temp = false;
        $interval.cancel($scope.interval);
      }
      $scope.showscore = Math.round($scope.correct / $scope.questions.length * 100);
      $scope.minuteleft = parseInt(($scope.totalsecoriginal - $scope.totalsec) / 60, 10);

      $scope.pos = 0;
      return false;
    }
    $scope.question = $scope.questions[$scope.pos][0];
    $scope.chA = $scope.questions[$scope.pos][1];
    $scope.chB = $scope.questions[$scope.pos][2];
    $scope.chC = $scope.questions[$scope.pos][3];
  }

  $scope.checkAnswer = function() {
    $scope.choices = angular.element(document.getElementsByName('choices'));
    $scope.choice = -1;
    for (var i = 0; i < $scope.choices.length; i++) {
      if ($scope.choices[i].checked) {
        $scope.choice = $scope.choices[i].value;
        $scope.choices[i].checked = false;
      }
    }
    if ($scope.choice == $scope.questions[$scope.pos][4]) {
      $scope.correct++;
    }
    $scope.pos++;
    $scope.renderQuestion();

  }
  $scope.renderQuestion();

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>

  <div id="Holder">
    <div id="Header"></div>
    <div id="NavBar">
      <ul>
        <li><a href="Loginpage.htm"> Login</a></li>
        <li><a href="Registrationpage.htm">Registration</a></li>
      </ul>
    </div>
    <div id="Content">
      <div id="PageHeading">
        <h1><marquee direction="right" behavior="alternate">All the Best</marquee></h1>
      </div>
      <div id="ContentLeft">
        <h2></h2>
        <br>
        <img id="online_start">
        <br>
        <h6>Online Examination System(OES) is a Multiple Choice Questions(MCQ) based 
examination system that provides an easy to use environment for both 
Test Conducters and Students appearing for Examination.</h6>
      </div>
      <div id="ContentRight">
        <section class="loginform_cf">
          <div ng-app="MyApp" ng-controller="MyController" ng-init="StartTimer()">
            <table>
              <tr>
                <td id="test_status" style="text-align:left">
                  <h3 ng-show='ques'>Question {{pos+1}} of {{questions.length}}</h3>
                  <h3 ng-hide='ques'>Test Completed  </h3>
                </td>
                <td ng-show='ques'> Exam Starts :<span ng-bind="hhmmss">  </span> </td>
                <td ng-show='ques'> Exam Ends : {{currentTime | date:'hh:mm:ss a'}} </td>
              </tr>
              <tr>
                <td id="test" colspan="3">
                  <div ng-show="ques">
                    <h3>{{question}}</h3>
                    <input type='radio' name='choices' value='A'>{{chA}}
                    <br>
                    <input type='radio' name='choices' value='B'>{{chB}}
                    <br>
                    <input type='radio' name='choices' value='C'>{{chC}}
                    <br>
                    <br>
                    <button ng-click='checkAnswer()'>Next</button>
                  </div>
                  <div ng-hide='ques'>
                    <h3>You got {{correct}} correct of {{questions.length}} questions</h3>
                    <h3> Your Grade :  {{showscore}}% </h3>
                    <h4>Exam Finished in Time :{{minuteleft}} Minutes {{sec}} Seconds</h4>
                    <button ng-click='EndExam()'>End the Exam</button>
                  </div>
                  <br>
                  <br>
                </td>
              </tr>
            </table>
            <br> Your Left Time is :{{min}} Minutes {{sec}} Seconds
            <br>
          </div>
          <br>
        </section>
      </div>
    </div>
    <div id="Footer">Developed by - K.P.RAJU</div>
  </div>
</body>

#1


0  

To try solve your 1st problem, try putting alert inside timeout, like

要尝试解决您的第一个问题,请尝试将警报置于超时范围内,例如

  $timeout(function() {
        $window.alert("Time Up");
    },0);

Because JavaScript is single thread, AngularJS must be run in callback mode, so the alert is called before AngularJS rendering getting called.

因为JavaScript是单线程,所以AngularJS必须在回调模式下运行,因此在调用AngularJS渲染之前调用警报。

2nd, sorry didn't get you

2,抱歉没有得到你

#2


0  

I have changed your code to angular and used interval to run the time and ng-show and ng-hide directives.

我已将您的代码更改为角度并使用间隔来运行时间和ng-show和ng-hide指令。

SCRIPT and HTML

脚本和HTML

var app = angular.module('MyApp', [])
app.controller('MyController', function($scope, $compile, $window, $interval, $timeout, $filter) {

  $scope.pos = 0, $scope.correct = 0, $scope.ques = true;

  $scope.questions = [
    ["Which of the following a is not a keyword in Java ?", "class", "interface", "extends", "C"],

    ["Which of the following is an interface ?", "Thread", "Date", "Calender", "A"],

    ["Which company released Java Version 8 ?", "Sun", "Oracle", "Adobe", "A"],

    ["What is the length of Java datatype int ?", "32 bit", "16 bit", "None", "C"],

    ["What is the default value of Java datatype boolean?", "true", "false", "0", "A"]
  ];


  $scope.totalsecoriginal = $scope.totalsec = 60;
  $scope.totalsec--;
  $scope.min = parseInt($scope.totalsec / 60, 10);
  $scope.sec = $scope.totalsec - ($scope.min * 60);
  $scope.date = new Date();
  $scope.hhmmss = $filter('date')(new Date(), 'hh:mm:ss a');

  $scope.currentTime = new Date();
  $scope.currentTime.setSeconds($scope.currentTime.getSeconds() + 60);


  function _(x) {
    console.log(angular.element(document.getElementById(x)));
    return angular.element(document.getElementById(x))[0];
  }
  $scope.interval = $interval(function() {
    if ($scope.sec === 0) {
      $scope.min--;
      $scope.sec = 60;
    }
    $scope.sec--;
  }, 1000);
  $scope.$watch('sec', function() {
    if ($scope.min === 0 && $scope.sec === 0) {
      $interval.cancel($scope.interval);
      window.alert('Time Up!!!');
      $scope.pos = $scope.questions.length;
      $scope.temp = true;
      $scope.renderQuestion();
    }

  })
  $scope.renderQuestion = function() {
    if ($scope.pos >= $scope.questions.length) {
      $scope.ques = false;
      if (!$scope.temp) { $scope.temp = false;
        $interval.cancel($scope.interval);
      }
      $scope.showscore = Math.round($scope.correct / $scope.questions.length * 100);
      $scope.minuteleft = parseInt(($scope.totalsecoriginal - $scope.totalsec) / 60, 10);

      $scope.pos = 0;
      return false;
    }
    $scope.question = $scope.questions[$scope.pos][0];
    $scope.chA = $scope.questions[$scope.pos][1];
    $scope.chB = $scope.questions[$scope.pos][2];
    $scope.chC = $scope.questions[$scope.pos][3];
  }

  $scope.checkAnswer = function() {
    $scope.choices = angular.element(document.getElementsByName('choices'));
    $scope.choice = -1;
    for (var i = 0; i < $scope.choices.length; i++) {
      if ($scope.choices[i].checked) {
        $scope.choice = $scope.choices[i].value;
        $scope.choices[i].checked = false;
      }
    }
    if ($scope.choice == $scope.questions[$scope.pos][4]) {
      $scope.correct++;
    }
    $scope.pos++;
    $scope.renderQuestion();

  }
  $scope.renderQuestion();

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>

  <div id="Holder">
    <div id="Header"></div>
    <div id="NavBar">
      <ul>
        <li><a href="Loginpage.htm"> Login</a></li>
        <li><a href="Registrationpage.htm">Registration</a></li>
      </ul>
    </div>
    <div id="Content">
      <div id="PageHeading">
        <h1><marquee direction="right" behavior="alternate">All the Best</marquee></h1>
      </div>
      <div id="ContentLeft">
        <h2></h2>
        <br>
        <img id="online_start">
        <br>
        <h6>Online Examination System(OES) is a Multiple Choice Questions(MCQ) based 
examination system that provides an easy to use environment for both 
Test Conducters and Students appearing for Examination.</h6>
      </div>
      <div id="ContentRight">
        <section class="loginform_cf">
          <div ng-app="MyApp" ng-controller="MyController" ng-init="StartTimer()">
            <table>
              <tr>
                <td id="test_status" style="text-align:left">
                  <h3 ng-show='ques'>Question {{pos+1}} of {{questions.length}}</h3>
                  <h3 ng-hide='ques'>Test Completed  </h3>
                </td>
                <td ng-show='ques'> Exam Starts :<span ng-bind="hhmmss">  </span> </td>
                <td ng-show='ques'> Exam Ends : {{currentTime | date:'hh:mm:ss a'}} </td>
              </tr>
              <tr>
                <td id="test" colspan="3">
                  <div ng-show="ques">
                    <h3>{{question}}</h3>
                    <input type='radio' name='choices' value='A'>{{chA}}
                    <br>
                    <input type='radio' name='choices' value='B'>{{chB}}
                    <br>
                    <input type='radio' name='choices' value='C'>{{chC}}
                    <br>
                    <br>
                    <button ng-click='checkAnswer()'>Next</button>
                  </div>
                  <div ng-hide='ques'>
                    <h3>You got {{correct}} correct of {{questions.length}} questions</h3>
                    <h3> Your Grade :  {{showscore}}% </h3>
                    <h4>Exam Finished in Time :{{minuteleft}} Minutes {{sec}} Seconds</h4>
                    <button ng-click='EndExam()'>End the Exam</button>
                  </div>
                  <br>
                  <br>
                </td>
              </tr>
            </table>
            <br> Your Left Time is :{{min}} Minutes {{sec}} Seconds
            <br>
          </div>
          <br>
        </section>
      </div>
    </div>
    <div id="Footer">Developed by - K.P.RAJU</div>
  </div>
</body>