Link AngularJS service array length property to the controller's scope through binding

I am attempting to connect the length of an array from another service to my controller's scope in the following manner:

app.controller('TestCtrl', function ($scope, safePostService) {
    $scope.count = safePostService.queue.length;

    $scope.addOne = function () {
        safePostService.post('/echo/json/', {
            json: JSON.stringify({
                text: 'some text',
                array: [1, 2, 'three'],
                object: {
                    par1: 'another text',
                    par2: [3, 2, 'one'],
                    par3: {}
                }
            }),
            delay: 3
        });
    };
});

This is my service:

app.service('safePostService', function ($http, $timeout) {
    var self = this;

    var syncInterval = 1000;
    var timeoutPromise;
    var sending = false;

    this.queue = [];

    this.post = function (url, data) {
        self.queue.push({
            url: url,
            data: data
        });
        synchronizeNow();
    };

    function synchronizeNow() {
        $timeout.cancel(timeoutPromise);
        synchronizeLoop();
    }

    function synchronizeLoop() {
        if (sending) return;
        sending = true;
        var item = self.queue[0];
        $http.post(item.url, item.data).
        success(function () {
            self.queue.shift();
            afterResponse(true);
        }).
        error(function () {
            afterResponse(false)
        });
    }

    function afterResponse(success) {
        sending = false;
        if (self.queue.length > 0) {
            timeoutPromise = $timeout(synchronizeLoop, (success) ? 50 : syncInterval);
        }
    }
});

The $scope.count continues to display as 0 and does not update.

Check out this fiddle: http://jsfiddle.net/kannix/CGWbq/

Answer №1

Angular should monitor changes in the safePostService.queue.

Here's one way to do it:

$scope.$watch(function() { return safePostService.queue.length; }, function(item) {
  $scope.count = item;
}, true);

Fiddle: http://jsfiddle.net/CGWbq/4/

If successful, you can remove an item from the queue array like this:

self.queue.shift();

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

What is the most efficient way to retrieve the current user's ID within Loopback?

Given the instability and deprecation of loopback.getCurrentContext(), what strategies can I use to accurately identify users when they interact with API endpoints? Is it feasible to include the token ID in the request payload for verification purposes? H ...

The jQuery script operates just one time

Recently, I encountered a small issue with my script. It only seems to work once - after that, I have to refresh the page in order to remove a favorite article (which the script is supposed to do). $("a.fav_no").on('click', function () { ...

Add a new row to the table when a dropdown option is selected, and remove the row when deleted. Ensure that the row is only added

Here is my specific requirement: I need a table with a default row containing a dropdown menu in the first column. When an option is selected from the dropdown, a new table row should be added with the same content as the main row and a delete button for ...

evaluation of three variables using short-circuit logic

I was quite surprised by the outcome of the code I wrote. It seemed like it wouldn't work because it was checking if something is not running and the ID matches a specific one, then executing the code regardless of the break size limit: if(!isRunning ...

Navbar remains visible despite ng-hide directive

I am having issues hiding a navbar based on the user's login status. Despite changing the $scope.loggedIn variable, the navbar does not hide as expected. Why is this happening? View: <nav> <div ng-controller="mainCtrl"> <!-- Lo ...

Why is `screen` important?

Recent articles in June 2020 discussing "how to utilize react testing library" often showcase a setup similar to the one below: import React from 'react'; import { render, screen } from '@testing-library/react'; import App from '. ...

Employing the Confirm() function within the onbeforeunload() event

Is there a way to prompt the user with a confirmation box before exiting a page using JavaScript? If the user clicks "OK", a function should be executed before leaving the page, and if they click "Cancel", the page should remain open. window.onbeforeunloa ...

An issue encountered with getServerSideProps in NextJS 12 is causing a HttpError stating that cookies are not iterable, leading

Currently, I have an application running smoothly on my localhost. However, when it comes to production, an unexpected error has popped up: Error: HttpError: cookies is not iterable at handleError (/usr/src/.next/server/chunks/6830.js:163:11) at sendReques ...

Eliminate repeated elements in a selection using an AngularJS custom directive

I am in the process of creating an events app that utilizes JSON data from Drupal to showcase events using AngularJS within a Drupal module. One of the keys in the JSON object is 'genre', which I'm utilizing in a select dropdown to allow use ...

What is the best way to store JSON encoded items in an array using square brackets?

Currently, I am utilizing Javascript along with NodeJS to dynamically generate an array of JSON objects. My goal is to store this array of JSON objects in a .json file for future reference. However, when I attempt to save the file, I encounter an issue whe ...

Is there a way to utilize a JavaScript function to transfer several chosen values from a select listbox to a different listbox when a button is clicked?

Is it possible to create a functionality where users can select multiple values from a first list and by clicking a button, those selected values are added to a second list? How can this be achieved through JavaScript? function Add() { //function here ...

Develop a JavaScript function to declare variables

I am currently attempting to develop a small memory game where the time is multiplied by the number of moves made by the player. Upon completion of all pairs, a JavaScript function is executed: function finish() { stopCount(); var cnt1 = $("#cou ...

When the clearOnBlur setting is set to false, Material UI Autocomplete will not

I recently encountered an issue in my project while using Material UI's Autocomplete feature. Despite setting the clearOnBlur property to false, the input field keeps getting cleared after losing focus. I need assistance in resolving this problem, an ...

When you hover over them, Material UI icons shrink in size due to the Border

I've been working on a React application that includes Material UI icons in the header. My goal is to add a border at the bottom of each icon when hovered over, but currently, the borders are too close to the icons. Another problem I'm facing is ...

The detailed record of this run can be accessed at:

npm ERR! code ENOTEMPTY npm ERR! syscall rename npm ERR! path /usr/local/lib/node_modules/expo-cli npm ERR! dest /usr/local/lib/node_modules/.expo-cli-dKBr48UN npm ERR! errno -39 npm ERR! ENOTEMPTY: The directory cannot be renamed because ...

The search bar is visible on desktop screens and can be expanded on mobile devices

Check out my code snippet below. <style> #searchformfix { width: 50%; border-right: 1px solid #E5E5E5; border-left: 1px solid #E5E5E5; position: relative; background: #fff; height: 40px; display: inline-block; border: ...

In the realm of JavaScript, removing a DOM element can sometimes feel like an

For my project, I am using JavaScript, DOM, and AJAX to create pages. I am trying to figure out how to check if an element already exists and, if it does, remove it. This is what I have tried: var elementL = document.getElementById('divLogin'); ...

Utilize the key as the value for options within an object iteration in Vue.js

I have an object called colors, which stores color names: { "RD": "Red", "BL": "Blue", "GR": "Green", "YW": "Yellow" } In my dropdown menu, I'm generating options for each color in the colors object: <select v-model="colors"> <op ...

Strategies for transferring data between multiple controllers

Hello, I am just starting to learn AngularJS and have a basic understanding of controllers, which help transfer data to the view. Here is a sample controller based on what I know: angular.module('marksTotal',[]).controller('totalMarks&apos ...

Transform the collection of nested objects into an array of objects with identical key-value pairs and then output the result after each iteration

My goal is to transform an object with objects inside into an array of objects. The initial data looks like this: "data" :{ "tDetails": { "tName": "Limited", "tPay": "xyz" } ...