Is it possible for Angular.js timer finish event not to trigger data binding correctly?

I've been working on an AngularJS application that functions as a quiz by displaying pictures and prompting users to select the correct answer by clicking a button. The app is designed to store the user's answers in an object.

Everything seems to be running smoothly, except for an issue with the callback function not binding the value at times.

Specifically, when "Yes" is clicked, it should update my

img: {{questions[questionId]['imgUrl']}}
. However, despite having the following function in place:

$scope.yes = function() {
    //instantiate timer
    //save data
    $scope.questions[$scope.questionId]['userAnswer'] = 'a';
    //move to next question
    $scope.questionId++;
    startTimer('progressbar-timer');

};

There seems to be an issue with the callback function timeout() which is expected to perform the same task but fails to work properly. Although I receive the correct value in my console log, the

img: {{questions[questionId]['imgUrl']}}
isn't being updated.

Is there a need for extra binding here?

<!DOCTYPE html>
<html lang="en-US">
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<!-- compiled CSS -->
<link rel="stylesheet" type="text/css" href="bower_components/bootstrap/docs/assets/css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="bower_components/bootstrap/docs/assets/css/bootstrap-responsive.css" />


<!-- compiled JavaScript -->
<script type="text/javascript" src="dist/assets/js/angular-timer-bower.js"></script>
<script type="text/javascript" src="dist/assets/js/angular-timer-all.min.js"></script>

<body>

<div ng-app="ajokoeApp" ng-controller="testCtrl">


  <br>
  question: {{questions[questionId]['question']}}
  img: {{questions[questionId]['imgUrl']}}


  <button class="btn" ng-click="yes()">Yes</button>
  <button class="btn" ng-click="no()">No</button>
  <button class="btn" ng-click="notSure()">Not Sure</button>
<section id="progressbar-timer">
  <timer id="countdown" interval="1000" countdown="5" finish-callback="timeout()">
      Remaining time : {{countdown}} second{{secondsS}} ({{progressBar}}%). Activity? {{displayProgressActive}} {{kysymys}}
      <div class="progress progress-striped {{displayProgressActive}}" style="height: 30px;">
          <div class="bar" style="min-width: 2em; height: 30px; width: {{progressBar}}%;">
              {{countdown}}
          </div>
      </div>
  </timer>
</section>

<h3 class="counter">
    <timer countdown="5" interval="1000" finish-callback="timeout.finished()">{{seconds}} second{{secondsS}} </timer>
</h3>
Timer: <span class="timer-status">{{timeout.status}}</span>




</div>

  <script>
  angular.module('ajokoeApp', ['timer']).controller('testCtrl', function($scope) {
      $scope.questions = [
          {id: 0, question:'Can i drive straight?',answer:'a',userAnswer:'',imgUrl:'1.jpg'},
          {id: 1, question:'May i turn left?',answer:'b',userAnswer:'',imgUrl:'2.jpg'},
          {id: 2, question:'MAy i turn right?',answer:'a',userAnswer:'', imgUrl:'3.jpg'}
          ];
      //functions
      $scope.questionId = 0;
      $scope.yes = function() {
        //instantiate timer
        //save data
        $scope.questions[$scope.questionId]['userAnswer'] = 'a';
        //move to next question
        $scope.questionId++;
        startTimer('progressbar-timer');

      };
      $scope.no = function() {
        $scope.questions[$scope.questionId]['userAnswer'] = 'b';
        $scope.questionId++;
        startTimer('progressbar-timer');

      };
      $scope.notSure = function() {
        $scope.questions[$scope.questionId]['userAnswer'] = 'c';
        $scope.questionId++;
        startTimer('progressbar-timer');

      };
      $scope.timeout = function() {
        startTimer('progressbar-timer');
        $scope.questions[$scope.questionId]['userAnswer'] = 'c';
        $scope.questionId++;
        startTimer('progressbar-timer');
      };

    //Debug
    console.log($scope.questions);
  });
  </script>

</body>
</html>

Answer №1

I encountered a similar issue in my application and managed to resolve it by implementing the following solution: To modify each variable within the scope that needs to be changed, ensure that the modification is enclosed within $scope.$apply().

Instead of:

 $scope.no = function() {
   $scope.questions[$scope.questionId]['userAnswer'] = 'b';
   $scope.questionId++;
   startTimer('progressbar-timer');
 };

... consider encapsulating the code with $scope.$apply():

 $scope.no = function() {
   $scope.apply(function() {
      $scope.questions[$scope.questionId]['userAnswer'] = 'b';
      $scope.questionId++;
      startTimer('progressbar-timer');
   });
 };

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Begin the input box with some text

Currently, I am trying to incorporate a form field that automatically adds "http://" when clicked or typed into by a user. Below is the code snippet I have been using: <script type="text/javascript"> var input = $( "#website" ); input.val( input ...

I must add and display a tab for permissions

I am currently using the material UI tab for my project. My goal is to display the tab only when the permission is set to true. I have successfully achieved this functionality, but the issue arises when the permission is false. It results in an error that ...

Unusual quirks in javascript variables when used with arrays

Unsure if this question has been asked previously. Nevertheless, I couldn't find it anywhere. I've observed a peculiar behavior that seems to occur only with arrays. Here is the typical behavior I anticipate from variables: var k = 10, m = ...

Converting JSON object settings to a string causes an error as it is not a valid function

For my project, I have been provided with a JSON object that contains various settings, some being strings and others booleans. One thing I am struggling with is adding an animation name from the object that is stored in a variable. aniFx.move(inner, { ...

Express: adding a question mark to the URL when submitting the form

Upon submitting a form with a "?" in the URL, I noticed that when posting it redirects me to the page and still returns a "?" in the URL. Directory: server.js, index.html, package.json, package-lock, src/models/form.js server.js: const express = require( ...

Incorporate validation features within a jQuery method

I am struggling with some HTML and jQuery code that generates links based on user input. HTML <input type="text" id="text" placeholder="Enter text" autofocus /> <a id="link1" class="btn btn-info" href="#" target="_blank"> Search 1 </a> ...

Angular-schema-form: Understanding the Purpose of an Empty Array

Utilizing angular-schema-form in my current project, I am attempting to introduce an empty array into my model. Initially, I assumed that the array type schema form would not contain any elements, but to my surprise, it automatically inserted an object in ...

Discovering a solution to extract a value from an Array of objects without explicitly referencing the key has proven to be quite challenging, as my extensive online research has failed to yield any similar or closely related problems

So I had this specific constant value const uniqueObjArr = [ { asdfgfjhjkl:"example 123" }, { qwertyuiop:"example 456" }, { zxcvbnmqwerty:"example 678" }, ] I aim to retrieve the ...

An error of undefined Angular Service/Factory has occurred

I created a factory service called siteCollection: spApp.factory('siteCollection', function(){ return { usersObject : [], getUsers : function (){ $().SPServices({ operation: "GetUserCollectionFromSite", completef ...

Tips for extracting only a portion of the JavaScript timestamp

I have a JavaScript timestamp that reads Tue Sep 30 2014 12:02:50 GMT-0400 (EDT). When I use the .getTime() method, I get 1412092970.768 Typically, this timestamp represents a specific time of today. My question is whether it's possible to extract o ...

Can you explain the concept of binding and unbinding in jQuery?

Can you explain the concepts of binding and unbinding in jQuery in simple terms for someone who learns slowly? ...

Is there a way to modify the variable in order to switch the font of the heading every second using CSS and JavaScript?

I'm trying to create a heading that changes fonts every second, but I'm having trouble changing the variable to set it to another font. Check out my code here. Despite watching tutorials, everything seemed too confusing. var root = document.q ...

Trouble locating Angular module while referencing script as an ES6 module

Check out this simple plunk here. My goal is to reference the app.js file as an ES6 module by setting the type attribute of the script tag to module. However, when I add the type attribute, Angular is unable to find the module. If I remove it, then it work ...

The integration of signalR with jquery mobile is posing several challenges

Recently, I started working with jquery mobile and signalR to implement a calling feature in my mobile app. However, I encountered an error that looks like this: http://localhost:2286/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%2 ...

Displaying 100,000 sprites with a faint 0.1 opacity, utilizing see-through backgrounds and crisp antialiasing

In my current setup, I have the following key pieces of code: Renderer renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, canvas: canvas }); Textures dot: THREE.ImageUtils.loadTexture('./assets/images/dot.png') Material ...

There seems to be an error with cheeriojs regarding the initialization of exports.load

I am currently using cheeriojs for web scraping, but I am encountering an issue after loading the body into cheerio. Although the body appears to be well-formatted HTML code, I am receiving errors such as exports.load.initialize. This is preventing me fr ...

Tips for embedding a custom directive within a ui-bootstrap tooltip

Here is the code snippet that I am working with: // Code Example <span> hello world! </span> // Custom Directive 'use strict'; var referenceFieldTemplate = require('./reference-field.html'); module.exports = direct ...

using an external JavaScript function in the MongoDB shell

In my case, I have JavaScript functions that are stored in a JSON file: functions={} functions.a = function(){ return "returned" } I've come across tutorials suggesting that by importing this JSON file, I should be able to use these ...

Would it be expected for these two JQuery functions to exhibit identical behaviors?

If I have the following two JQuery functions - The first one is functional: $("#myLink_931").click(function () { $(".931").toggle(); }); The second one, however, does not work as expected: $("#myLink_931").click(function () { var class_name = $(thi ...

Sending URL parameters from a React frontend to an Express API call involves crafting the request URL with

I'm currently working on a project where I need to make a fetch request from React to Express. The API URL requires parameters, but I want the last part of the URL to be dynamic. How can I pass a parameter from React to the Express API URL? Here' ...