Automatically updating client-side values in AngularJS using setInterval()

Implementing a value calculator on the client side using AngularJS. I need to update the main value of the calculator every 5 minutes with setInterval().

This is my AngularJS code:

 $http({method: 'GET', url: '../assets/sources.json'}).success(function(data)
   {
      $scope.values = data; // response data

      $scope.getSourceValue = function(){

         if ($scope.source == "test") {

            return $scope.values.test["last"]

         } else if ($scope.source == "test"){

            return $scope.values.test1["last"]

         } else if ($scope.source == "test2"){

            return $scope.values["test2"]["last"]

         } else {

            return -1
         };

      } // getSource
    } 

In the client side:

<strong><h1> {{getSourceValue()|currency}}</strong></h1>

Any guidance would be greatly appreciated.

Thank you in advance.

UPDATE:

{
    "timestamp": "Sun Sep 14 2014, 01:40:03",
    "bitstamp": {
        "display_URL": "http://www.bitstamp.net",
        "display_name": "Bitstamp",
        "currency": "BTC",
        "last": 477.6
    },
    "btc-e": {
        "display_URL": "http://www.btc-e.com",
        "display_name": "BTC-e",
        "currency": "BTC",
        "last": 471.5
    },
    "bitcoinaverage": {
        "display_URL": "http://api.bitcoinaverage.com",
        "display_name": "BitcoinAverage",
        "currency": "BTC",
        "last": 479.23
    },
    "geeklab": {
        "display_URL": "http://ws.geeklab.com.ar",
        "display_name": "Geeklab",
        "currency": "ARS",
        "blue": 14.35
    }
}

Answer №1

Here's the solution I came up with for someone else. In this approach:

angular.module('test', [])

   .controller('test', function($scope, $http, $filter, $interval) {



      var stop;

      if(!angular.isDefined(stop)) {
         stop = $interval(function(){


               $http({method: 'GET', url: '../assets/sources.json'}).success(function(data)
               {
                  $scope.values = data; // response data

                  $scope.svalue = 0;

                  $scope.getSourceValue = function(){

                     if ($scope.source == "bitcoinaverage.com") {

                        $scope.svalue = $scope.values.bitcoinaverage["last"]

                     } else if ($scope.source == "bitstamp.net"){

                        $scope.svalue = $scope.values.bitstamp["last"]

                     } else if ($scope.source == "btc-e.com"){

                        $scope.svalue = $scope.values["btc-e"]["last"]

                     } else {

                        $scope.svalue = -1
                     };

                  } // getSource


            });//  /success()


         }, 40000);
      }


}); /*Controller*/

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 three.js, webGL, and GLSL through the magic of random

When using three.js to call a fragment shader, I have a shader that specifies a color for my material in rgb format. I am trying to figure out a way to multiply those colors by a random value. The code I currently have is as follows: gl_FragColor = vec4( ...

ng-click event triggers twice in directive-driven navigation

I have a directive that I'm using for my navigation, but when both ng-clicks are triggered, they fire twice. I've looked at similar questions here, but can't seem to figure it out. Any help would be appreciated. The HTML element <nav ng ...

Executing axios calls within other axios calls and altering state in React before all calls have completed

Currently, I am working on implementing nested axios calls to create the desired object by making multiple API requests. However, I am facing an issue where the state updates before all requests have finished, causing my table to populate entry by entry ...

Using Typescript to create an asynchronous function without explicitly declaring a Promise

When you examine TypeScript's async function, you may notice the redundancy with "async" and "Promise<type>". public async test(): Promise<string> { return "Test"; } Is there a way to configure TypeScript to handle async types ...

Toggling with Jquery when an image is clicked

I'm trying to wrap my head around the functionality of jquery toggle. My goal is to toggle to the next anchor element with the class plr-anchor when an image with the class go_down is clicked. The information is being populated using maps. Javascript ...

Is it no longer possible to export static pages in Next.js 14?

I'm currently experiencing a problem where my CSS styles are not being exported when I try to convert my project into static HTML pages. Here is the configuration in my next.config.js file: ** @type {import('next').NextConfig} */ const next ...

Failed verification of C-Lang in React-Hardware/Particle

Currently, I am utilizing React, React Hardware ([https://github.com/iamdustan/react-hardware/]), and Johnny-Five along with the Particle Photon. The error stack displayed below is what pops up when executing my lib/app.js file: # Fatal error in ../deps/v ...

Utilize JQuery to identify and select every parent element, then retrieve the height of the first child element and adjust the height of the

Recently, I developed a PHP script that pulls news and case posts from a database. The HTML structure used for displaying these posts is as follows: <a href='/post/placeholder'> <div class='col nopadding col12-12 counter'> ...

What steps should be taken to resolve the error message "TypeError: Cannot read properties of undefined (reading 'toLowerCase')?"

After creating a basic search bar, I encountered an issue when typing in it for the first time: TypeError: Cannot read properties of undefined (reading 'toLowerCase') However, when I closed the pop-up and tried again, the search bar worked prope ...

When utilizing VueJs, it's not possible to retrieve a data property from within a function

I am encountering a challenge when trying to access the data property within the function. Despite my efforts, I seem to be missing something crucial and unable to pinpoint what it is. Here is my class: export default { name: "Contact", component ...

Create new objects in a Laravel application by generating JSON and then assigning them to a variable

I created a function that retrieves all max offers from the maxoffers table: public function maxoffers($id) { $offers = Maxoffer::where('article_id', $id)->latest()->get(['id', 'price', 'start', & ...

The format of the date cannot be modified when using DesktopDatePicker as a React Component

I've been attempting to modify the appearance of the component, but the UI keeps showing the date in month-year format. <DesktopDatePicker inputVariant="outlined" label="Pick-up date" id="date ...

My chart's data gets misaligned when I resize the window, causing issues with the d3

I have 5 HTML elements with the class "container" that will contain 5 SVG images. The ids of these elements are generated programmatically and consist of numbers: <div id="svg-container-total"></div> <div id="svg-container-3"></div> ...

Searching DynamoDB in node.js using mapped items

In my DynamoDB table, I am trying to retrieve all Items where the Review.ID matches 123. Item: { id: 1, review: { Id: 123, step1: 456, step2: 789, step3: 1234, }, // Add more items here }, Item: { id: 2, review: { Id: 123 ...

Finding the title of a checkbox within a specific row

I am facing an issue where I have a checkbox inside a grid, and I need to determine the header name of that specific element upon clicking a button located outside the grid. The structure of my grid is as follows: <thead class="k-grid-header"> &l ...

A guide to implementing angularjs app.service and $q in typescript

I am fairly new to TypeScript and AngularJS and I am struggling to find the correct answer for my issue. Below is the relevant code snippet: export class SidenavController { static $inject = ['$scope', '$mdSidenav']; constructor(p ...

Encounter the error message "Socket closure detected" upon running JSReport in the background on a RHEL system

I'm encountering an issue with JSReport at www.jsreport.net. When I run npm start --production in the background, everything seems to be working fine. But as soon as I close this session, an error pops up: Error occurred - This socket is closed. Sta ...

JavaScript Code: Empty a text box when a different one is active

Looking for a solution to clear the content of one textbox when the user interacts with another in HTML and JavaScript. <input id="tb1" type="text" name="textbox1"> <input id="tb2" type="text" name="textbox2"> Seeking JavaScript code that wil ...

The b-link component in bootstrap-vue is not displaying the text content or inner HTML as expected

Having trouble retrieving the textContent from a blink element and modifying it. Interestingly, when attempting the same process with a tag or div tag, it works without any issues. <b-link :ref="index" v-b-toggle="`${index}`" @c ...

Exploring the Wonderful World of Styled Components

I have a query regarding styled components and how they interact when one is referenced within another. While I've looked at the official documentation with the Link example, I'm still unclear on the exact behavior when one styled component refe ...