Angular JS Retrieving Data in the Background with the Assistance of $timeout or $interval Service

Looking to fetch data from a webapi in the background using either the $timeout or $interval service in Angular JS.

I have some concerns about how the $timeout and $interval services work. I've run into issues when incorporating these services into my controller. Here are some observations from my current development: - There is a presence of multiple nested controllers within the application. - Upon transitioning from one state to another, the $timeout or $interval service is triggered again. (This can be prevented by cancelling the timer on Scope Destroy) - However, how do we go about maintaining timer information?

Is it possible to create a service or factory to address this issue?

Answer №1

Of course, it is possible to utilize a factory for this purpose. This approach ensures that the $timeout and $interval are instantiated only once.

By creating a factory similar to the one outlined below, you can easily share data obtained or generated within an $interval with your controller (refer to the bottom section):

angular.module('app')
  .factory('interval', interval);

interval.$inject = ['$interval'];

function interval($interval) {
  var counter = {};
  activate();

  return {
    counter: counter
  };

  function activate() {
    $interval(increaseCounter, 1000);
  }

  function increaseCounter() {
    if(angular.isUndefined(counter.count)) {
      counter.count = 0;
    } else {
      counter.count++;
    }
  }
}

Additionally, here's the corresponding controller:

angular.module('app')
  .controller('TestController', testController);

testController.$inject = ['interval'];

function testController(interval) {
  var vm = this;
  this.counter = interval.counter;
}

You can now showcase the counter (or any retrieved data from the $interval) in the view as follows:

<div ng-controller="TestController as ctrl">
  {{ctrl.counter.count}}
</div>

It's worth noting that directly sharing count isn't feasible due to JavaScript passing values by reference/value peculiarities.

Feel free to access a functional fiddle: https://jsfiddle.net/m5hw5w1o/

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

Bug in toFixed causing incorrect results

function calculateTaxAndTotalRent(rent) { var phoneCharges = parseFloat($('#phone_charges').val()); phoneCharges = phoneCharges.toFixed(2); rent = parseFloat(rent); rent = rent.toFixed(2); var tax = parseFloat((rent * 15) / 1 ...

Troubleshooting a ThreeJS Issue: the Mystery of the Malfunction

I have a ribbon showcasing various thumbnails. These thumbnails are painted on a canvas and then added to a Texture. var texture = new THREE.Texture(textureCanvas); The mesh is generated as shown below loader.load('mesh_blender.js', functi ...

Cordova application encounters failure in making AJAX call to localhost with error code ::ERR_CONNECTION_REFUSED

I have a node.js (express) web application running on localhost:3000. Currently, I am working on developing a mobile app using cordova. Within my express app, I have a defined route 'localhost:3000/tweets' that retrieves tweets from the Twitter ...

Exploring the Magic of Class Variable Destructuring in React

Is there a simpler method to break down a prop object and assign them to variables of the same name in the class? I am familiar with ({ first: this.first, second: this.second, } = props) however, it can get complicated when dealing with numerous variable ...

Access the latest data within Sails' Waterline prior to the update process

When using Sails' Waterline, I am tasked with comparing the previous value to the new one and assigning a new attribute based on certain conditions. For instance: beforeUpdate: function(newValues, callback) { if(/* currentValues */.age > newVal ...

Parsing JSON data using PHP and AJAX decoding

I have been searching for a way to pass parameters between the server and client, but I am struggling to find a solution that works. Despite reading extensively online, I have not been able to come up with a functioning solution. Client Side function sen ...

Using Jquery to detect if there are any Space characters in the user input

In my form, users are required to set up a new Username. The problem arises when they include a space in their username, which I want to prevent. Currently, I am able to detect the presence of a space with this code: var hasSpace = $('#usernameValue ...

What is a method to raise the height when scrolling down without reducing it when scrolling up?

For my One Page project, I want a DIV element to increase in height when scrolling down, but maintain that increased height when scrolling up. Currently, I am utilizing JQuery with the code snippet below: $(function(){ $(window).scroll(function() { ...

Code has been loaded successfully for react-loadable Chunks, however it has not been

Encountering a problem while trying to implement chunks in my React app using react-loadable Everything functions perfectly on webpack-dev-server in development mode. However, when I build the project and deploy it to the server, async components are ...

Why does the method Array.concat on an extended class remove empty values in Node.js version 8.9.3?

I am experimenting with adding new functionality to Arrays in node.js without altering the original Array class to avoid any unintended consequences in other modules. During testing, I encountered some failures which led me to discover that the behavior o ...

Utilizing Custom Script Tag Types in Visual Studio for Enhanced HTML Template Functionality and Improved Syntax Highlighting

Currently, I am utilizing Visual Studio 2012 for editing HTML and JavaScript. My approach involves inserting templates using partial views in inline script tags (view code below). The use of AngularJS, a Javascript framework, dictates that the type must be ...

Utilizing Vue.js to share a single array of data across two distinct input lists

For a clearer understanding of my requirements, I have put together a demo on JSFiddle: https://jsfiddle.net/silentway/aro5kq7u/3/ The code snippet is presented below: <script src="https://cdn.jsdelivr.net/npm/vue"></script> <div id=" ...

Enhancing Performance with Web Workers in Angular CLI

Lately, I've been tackling a challenging issue with my Angular app - heavy computation on the client side leading to UI blockage. My solution? Utilizing Web Workers in my Angular CLI project to separate UI tasks into one thread and heavy processing in ...

Confirm the session validity before invoking the web service function from an ajax function triggered by clicking a button

I am experiencing a complex issue. On a page, users input data and then click on a button to save all the parameters into a JSON object. After saving locally, they click another button which triggers an ajax method that calls a web service method on the sa ...

Conceal the visibility of the popover in Onsen UI

Before anyone criticizes me for not trying existing solutions, I have attempted them and unfortunately, they did not work for me. I followed the suggestions in similar questions linked below without success: How to hide popover in onsen ui I am puzzled as ...

Explore button that gradually decreases max-height

I have a "Show More" button that expands a div by removing the css attribute max-height, but I want to add an animation similar to jQuery's slideToggle() function to smoothly reveal the rest of the content. This is the code I am using: <div id="P ...

Trouble accessing state when React child calls parent method

Within my project, I am working with 3 components that are nested as follows: App->GameList->GameItem The App (parent) component has a method that is triggered by the onClick event within the GameItem (child) component Upon clicking the GameItem co ...

Node.js: Leveraging Express to Compare URL Parameters and Handle Delete Requests with Array Values

Having some issues with the Express routes I set up for an array of objects and CRUD operations. Everything works smoothly except for the "Delete" operation. I am trying to delete an object by matching its URL parameter ID with the value of its key. Howev ...

Tips for successfully integrating .dae files into three.js for online execution on a web browser

Hey everyone, I'm an HTML developer who has never worked with WEBGL technology before. I've been trying to figure out how to pass a .dae file into 'three.js' by searching through numerous websites, but I haven't been successful. C ...

Is it possible to load multiple angular applications within a master angular shell application?

I am searching for a method to integrate multiple Angular applications into a single shell Angular application. The concept involves having different teams develop separate Angular apps that can be loaded within a main shell app visible to end users. Thi ...