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

Exploring the World of React JS by Diving into Backend Data

Let's consider an application that consists of three pages: "HomePage" "PrivatePage" "UserManagementPage" In addition, there is a file called "BackendCommunication.js" responsible for handling communication with the backend. "Homepage.js" import Re ...

Tips on removing properties from an object recursively according to their key/value pairs

My current task involves removing specific children of an object based on whether their "size" key is set to 0. To achieve this, I am utilizing the npm package directory-tree to generate a JavaScript object representation of a chosen directory. The stru ...

The function is not valid due to an angular-parse argument

This is my first experience with using angular and parse.com. I encountered the following error: Error: Argument 'eventList' is not a function, got undefined when attempting to execute the following angular code: var main_app = angular.mod ...

Distributing utility functions universally throughout the entire React application

Is there a way to create global functions in React that can be imported into one file and shared across all pages? Currently, I have to import helper.tsx into each individual file where I want to use them. For example, the helper.tsx file exports functio ...

The vue-pdf is having trouble loading all pages due to an "undefined property" issue

I am currently utilizing the following technologies: Vue.js, vue-route, Vuetify, Firebase (with a database) and vue-pdf The issue I am facing involves attempting to load all pdf pages using "vue-pdf" plugin. However, when trying to read the pdf, I encoun ...

Another approach to utilize JavaScript for populating content into a <div> container?

Upon loading the page, I aim to display a message in the <div> element. Below is the HTML and JavaScript code I have implemented: <body onload="printMsg()"> <div id="write"></div> </body> function printMsg() { var no ...

Unexpected Type Error: Unable to Assign 'Render' Property to Undefined

At the moment, I am encountering these specific issues: An Uncaught TypeError: Cannot set property 'render' of undefined The element #main cannot be found This is the code that I currently have. Despite looking for solutions from various sourc ...

How to pass GetServerSideProps into Page component props in Next.js with custom _app.js

Having issues integrating GetServerSideProps into my Next.js app. Despite the network call successfully fetching data and generating the pageName.json, the response data is not being injected into the page props as expected. Below is a snippet of my page ...

What distinctions can be made between Controlled and Uncontrolled Components when using react-hooks-form?

Trying out the React Hooks form, I came across some interesting concepts like controlled and uncontrolled forms. Controlled Form <form onSubmit={handleSubmit(onSubmit)}> <input name="firstName" ref={register({ required: true })} /> ...

How can you confirm the validity of a dropdown menu using JavaScript?

<FORM NAME="form1" METHOD="POST" ACTION="survey.php"> <P>q1: How would you rate the performance of John Doe? <P> <INPUT TYPE='Radio' Name='q1' value='1' id='q1'>1 ...

Revamp your search experience with Algolia's Angular Instant Search: Design a personalized search box template

Custom Search Box Request: My goal is to implement an autosuggest search box using Algolia Angular instant search with an Angular Material design. To achieve this, I am planning to customize the search box component by replacing the standard <ais-sea ...

I created a custom discord.js-commando command to announce all the channels that my bot is currently active in, however, encountered an unexpected error

const Commando = require('discord.js-commando'); module.exports = class AnnounceCommand extends Commando.Command { constructor(client) { super(client, { name: 'announce', aliases: ['an'], ...

Determine the frequency of a specific key in an array of objects

original array: ................ [ { from: {_id: "60dd7c7950d9e01088e438e0"} }, { from: {_id: "60dd7c7950d9e01088e438e0"} }, { from: {_id: "60dd7e19e6b26621247a35cd"} } ] A new array is created to count the instances of each ...

Step-by-step guide on retrieving JSONP data from Angular service within view by utilizing expressions

I have been developing an Angular application that retrieves data from the Strava API. While experimenting with $http.get, I realized that separating the logic into a dedicated service would be more organized, allowing my controller to simply call the serv ...

Authorization setup encountered an issue: an unexpected character was found at the beginning of the JSON data on line 1, column

I'm currently in the process of setting up a login page for users on my website, using mongoose, express, bcrypt, and nodejs. However, I am encountering an issue when trying to input the username and password. The error message that I receive is as fo ...

I encountered a response error code 500 from the development server while using my emulator

As I embark on setting up the react-native environment for development, I encounter an error when executing the command react-native run-android. root@pc:~/l3/s2/DevMobMultipltm/Wakapp# ` A series of tasks are carried out including scanning folders for sy ...

Utilizing a keycode within the jQuery plugin without the need to explicitly pass it through options

I am currently working on developing a custom jQuery plugin. My goal is to be able to check the keyCode within the plugin without needing to pass it through as an option parameter. Below, you can see the code snippet that I'm using. It's a bit c ...

efforts to activate a "click" with the enter key are unsuccessful

I'm attempting to enhance user experience on my site by triggering the onclick event of a button when the enter key is pressed. I've tried various methods below, but all seem to have the same issue. Here is my HTML (using Pug): input#userIntere ...

The integration of Raphaeljs library with SmartPhones opens up a world of

I recently incorporated the incredible JavaScript library, RaphaelJS, into my website to create maps, animations, and interactive features. Interestingly, I have observed that the scripts utilizing this library function seamlessly on iPhones but encounter ...

Adjusting the line-height in CSS dynamically based on the length of characters using jQuery

I am facing an issue with the Twitter widget on my website where our company's latest tweet sometimes gets cut off if it exceeds a certain length. I want to dynamically adjust the line-height CSS property of the element based on the tweet's chara ...