Troubleshooting AngularJS: Issues with dividing by scope variable

I am using angular-timer.

This particular code snippet works fine:

{{ (seconds / 10) * 100 }}

But when I try this one, it doesn't work as expected:

{{ (seconds / secondsToAnswer ) * 100 }

(it gives NaN as the result)

Even though I have defined secondsToAnswer as 10 in the controller: $scope.secondsToAnswer = 10; This issue persists outside the directive too.

Here is the full code for reference:

HTML

<timer interval="1000">
  <div class="progress">
    <div class="progress-bar progress-bar-info progress-bar-striped"
         role="progressbar"
         aria-valuenow="20"
         aria-valuemin="0"
         aria-valuemax="100"
         style="width: {{ (seconds / secondsToAnswer) * 100 }}%">
    </div>
  </div>
</timer>

JS

'use strict';

vocabApp.controller('PracticeController', function ($scope) {

  $scope.expressions = [
    { expression:'cat', meaning:'macska' },
    { expression:'dog', meaning:'kutya' },
    { expression:'whale', meaning:'bálna' }
  ];

  //$scope.timerRunning = true;

  $scope.startTimer = function () {
    $scope.secondsToAnswer = 10;
    $scope.$broadcast('timer-start');
    $scope.timerRunning = true;
  };

  $scope.stopTimer = function () {
    $scope.$broadcast('timer-stop');
    $scope.timerRunning = false;
  };

  $scope.$on('timer-stopped', function (event, args) {
    console.log('timer-stopped args = ', args);
  });

})

Answer №1

The reason is that $scope.secondsToAnswer = 10; will not be defined until the startTimer function is called, so it remains undefined until then.

To fix this issue, place $scope.secondsToAnswer = 10; at the beginning of your controller code to ensure it is defined from the start.

Answer №2

It seems like the issue originates from two different sources. To begin with, as highlighted by Sander_P, it is important to note that $scope.secondsToAnswer should be declared at the outset of your controller rather than within the startTimer function. Another aspect to consider is that while your controller encloses the timer directive, it should actually be contained inside it.

As an illustration:

 <timer interval="1000">
        <div ng-controller="PracticeController" class="progress">
            <div class="progress-bar progress-bar-info progress-bar-striped" 
                 role="progressbar"
                 aria-valuenow="20"
                 aria-valuemin="0"
                 aria-valuemax="100"
                 style="width: {{ (seconds / secondsToAnswer) * 100 }}%">
            </div>
        </div>
  </timer>

You can view a functional jsfiddle demonstration here:

var vocabApp = angular.module("APP", ['timer']);
vocabApp.controller('PracticeController', function ($scope) {

    $scope.secondsToAnswer = 100;

    $scope.expressions = [{
        expression: 'cat',
        meaning: 'macska'
    }, {
        expression: 'dog',
        meaning: 'kutya'
    }, {
        expression: 'whale',
        meaning: 'bálna'
    }];

    //$scope.timerRunning = true;

    $scope.startTimer = function () {
        $scope.$broadcast('timer-start');
        $scope.timerRunning = true;
    };

    $scope.stopTimer = function () {
        $scope.$broadcast('timer-stop');
        $scope.timerRunning = false;
    };

    $scope.$on('timer-stopped', function (event, args) {
        console.log('timer-stopped args = ', args);
    });

});

Answer №3

There are two key points to consider:

  1. For proper functionality, it is important to declare the $scope.secondsToAnswer variable globally outside of the function instead of within the startTimer function.

  2. When working with HTML code, ensure to encapsulate the designated scope area appropriately. For example, enclose it within the timer directive in this scenario.

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

Running nodejs scripts within my HTML and JavaScript code

Using express, I send an HTML file to incoming GET requests: app.get('/', function(req, res) { res.sendFile(path.join(__dirname + '/public/index.html')); }); Within that HTML file, I included another JavaScript file, script.js, us ...

Explore search results that include values nested within map arrays

I have an array with multiple objects, each containing a nested array of subValues. My goal is to filter components based on search criteria. While I can successfully search the parent level objects' values, I am struggling with filtering based on the ...

Sending a parameter between files in a React application: a step-by-step guide

I am currently working on a Pokedex website where I have Pokemon cards displaying data from a JSON file. When a user clicks on a card, a modal view appears with more detailed information about that specific card. I need help in ensuring that only the deta ...

Is it possible to showcase D3 charts on an .epub file?

For my research project, I am exploring the possibilities of .epub files and experimenting with embedding JavaScript code to display data visualizations. I am currently using calibre to convert an HTML file containing D3 scatterplots into an .epub. The s ...

Utilizing React Material-Table to Trigger a React Component through Table Actions

I have set up a datatable using the code below. <MaterialTable icons={tableIcons} title={title} columns={columns} data={data} actions={[ { icon: () => <Edit />, t ...

Arranging a nested JSON array directly

Below is the structure of my JSON data : Root |- cells [] |-Individual cells with the following |- Facts (Object) |- Measures (Object) |- Key value pairs |- other valu ...

React in response after waiting for the DOM element - Reactjs

Hey there! I'm working with a class component that looks like this: class SomeComponent extends Component { componentDidMount = () => { const divElement = document.getElementbyId('id'); // it may take a few moments for this ele ...

Is it possible to prevent a webpage from being refreshed?

I need help with an HTML page that puts the worker on pause time which will be subtracted from his/her day job. The issue is that when he/she refreshes the page, the timer starts from the beginning automatically. I want it to continue without resetting. Is ...

Encountering difficulties in storing array data into MongoDB collection

I am facing an issue with connecting to two different MongoDB instances using different URLs. One URL points to a remote connection string while the other one is for a local MongoDB instance. Initially, I establish a connection to MongoDB using MongoClient ...

deciphering JSON objects based on specific keys

Struggling to complete a seemingly straightforward task has left me feeling frustrated. In the header of my HTML page, I have an external car dealer API being called. At the bottom of the page, there is another external .js file containing a series of if- ...

Auto-stop the EC-2 instance after a specified period of time utilizing SDK

Is it possible to automatically terminate an EC-2 instance after a specific time, such as 2 hours from when it was created? I am currently utilizing NodeJS for my AWS EC-2 operations. Is there a specific parameter that needs to be included when creating ...

What causes a function to be returned as null when it is appended or assigned as textContent?

There's something I've been trying to figure out and I'm curious to get an answer on why it behaves this way. const print_html = (param) => { let container = document.querySelector('Container'); console.log(test_function(pa ...

Using Three JS: Import an OBJ file, move it to the center of the scene, and rotate around it

I am trying to figure out how to load an OBJ file and translate its coordinates to the world origin (0,0,0) in order to make orbit controls function smoothly without using Pivot points. My goal is to automatically translate random OBJ objects with differe ...

What is the best way to create two MUI accordions stacked on top of each other to each occupy 50% of the parent container, with only their contents scrolling

I am looking to create a layout with two React MUI Accordions stacked vertically in a div. Each accordion should expand independently, taking up the available space while leaving the other's label untouched. When both are expanded, they should collect ...

Retrieving Information from an Angular 2 Component

Struggling to figure this out, I am attempting to dynamically add user video data that includes a video URL. My goal is to access the data from the component so I can use it in my HTML. I've attempted the following approach. app.component.ts import ...

Using THREE.js in the pre-render function

I am encountering difficulties with updating the positions of my enemies before rendering them. Instead of creating a separate update() function, I attempted to use an onBeforeRender() function attached to each enemy object. However, nothing seems to be ...

I'm new to Angular, so could you please explain this to me? I'm trying to understand the concept of `private todoItems: TodoItem[] = []`. I know `TodoItem` is an array that

//This pertains to the todoList class// The property name is todoItems, which is an array of TodoItem objects fetched from the TodoItem file. I am unable to make it private using "private todoItems: TodoItem[] = []," is this because of Dependency Injectio ...

Having difficulty showcasing API call results in a Vue.js component

I am currently experimenting with Vue.js in an attempt to showcase results from a Wikipedia API call within a component using the v-for directive. However, I seem to be encountering some backend issues that I cannot pinpoint. To access the jsFiddle link, ...

Encountering the error message "Cannot GET /" when trying to access the front page using Express.js

I am a beginner in Node.js. I have been learning through videos and documentation, and I started developing a site following an MVC structure. The node server appears to be working fine, but I am facing an issue where the front end displays 'Cannot GE ...

How to close an iframe with javascript or jquery?

I am working with a series of iframes on my website. I am trying to figure out how to close the last iframe in the list when a button is clicked. Can someone please provide guidance on how to achieve this? Specifically, I am looking to execute a window.cl ...