Stay in time with live updates using LoDash and AngularJS synchronization

I am currently developing an AngularJS Application where I am inserting records in the form of objects into an array.

After using LoDash to extract statistics from this data (you can find the relevant question here), I encountered an issue. The stats only update when I reload the page, but as a Single Page Application (SPA), I need them to update dynamically as I add new records to the array ($scope.recordlist).

Below is the key portion of the code:

var dataByMonth = _.groupBy($scope.recordlist, function(record) { 
    return moment(record.date, 'DD-MM-YYYY').format('MMMM YYYY'); 
});

dataByMonth = _.mapValues(dataByMonth, function(month) {
    var obj = {};
    obj.Cars = _.groupBy(month, 'car');
    obj.Drivers = _.groupBy(month, 'driver');

    _.each(obj, function(groupsValue, groupKey) {
        obj[groupKey] = _.mapValues(groupsValue, function(groupValue) {
            return _.reduce(groupValue, function(sum, trip) {
                sum['trips']++;
                sum['duration']+= moment.utc(trip.duration, 'HH:mm:ss');
                sum['total'] = moment.utc(sum.duration). format('HH:mm:ss')
                //addDuration(sum.duration, car.duration); 
                return sum;
            }, {trips: 0, duration: 0, total:0})
        });
    })

    return obj;
});

$scope.statistics = dataByMonth;

Can you help me identify what I missed?

Answer №1

If you follow these steps, you should achieve your desired outcome. Start by enclosing your code in a function and then utilize the $watch feature on $scope.recordlist. This will trigger the function whenever changes are detected.

$scope.refreshStats = function() {
    var dataByMonth = _.groupBy($scope.recordlist, function(record) { 
        return moment(record.date, 'DD-MM-YYYY').format('MMMM YYYY'); 
    });

    dataByMonth = _.mapValues(dataByMonth, function(month) {
        var obj = {};
        obj.Cars = _.groupBy(month, 'car');
        obj.Drivers = _.groupBy(month, 'driver');

        _.each(obj, function(groupsValue, groupKey) {
        obj[groupKey] = _.mapValues(groupsValue, function(groupValue) {
            return _.reduce(groupValue, function(sum, trip) {
                sum['trips']++;
                sum['duration']+= moment.utc(trip.duration, 'HH:mm:ss');
                sum['total'] = moment.utc(sum.duration).format('HH:mm:ss')
                //addDuration(sum.duration, car.duration); 
                return sum;
            }, {trips: 0, duration: 0, total:0})
        });
        })

        return obj;
    });

    $scope.statistics = dataByMonth;
};

$scope.refreshStats(); // initial load

$scope.$watch('recordlist', $scope.refreshStats, true); // updates without reloading

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

The child user interface component is failing to respond to keypress events within the parent component in an Angular project

I am facing a challenge in adding a keyboard shortcut to open a nested child UI Tab component through a keypress event. However, the Child nested tab can only be loaded after the Parent component is loaded first. Below is the structure of the UI tree: |-- ...

"When trying to access a jQuery ID, it is coming back as undefined even though the

I'm attempting to obtain the ID of a specific element, save it as a variable, and then utilize that ID value to interact with other elements in the same section bearing the identical ID. <div class="mainContent"> <div class="articleContent"& ...

Retrieve returned data using jQuery

How can I retrieve data when using the jQuery.get method? function send_data(pgId) { for(var i = 0; i < pgId.length; i++) { // $.get(url, data, success(data, textStatus, jqXHR)) $.get('index.php?page=' + pgId[i], pgId[ ...

Error occurred in AngularJS when trying to pass a parameter from an HTML page in order to retrieve data using

I am encountering an issue when attempting to pass a parameter from the HTML page to delete a row from the database. The http.get() method retrieves data for all books, and I am passing the ID for a specific book for deletion. However, I am facing a syntax ...

Is there a way to initiate a jquery function upon loading the page, while ensuring its continued user interaction?

On my webpage, there is a JavaScript function using jQuery that I want to automatically start when the page loads. At the same time, I want to ensure that users can still interact with this function. This particular function involves selecting a link tha ...

What is the best way to showcase JSON data while incorporating HTML tags in a React application?

My JSON data contains HTML tags interspersed within it and I have successfully fetched and displayed the data. See the code snippet below: componentDidMount() { this._callCake(); } _renderEachCake = () => { return ( <EachCake ...

Incorporate a single file into the source code using React just once

I am looking to add a JavaScript script to the body when a React Component renders, but I only want it to happen once. Here is the current code I have: const MyComponent: React.FC = () => { const script = document.createElement('script'); ...

AngularJS Router and .NET backend - troubleshooting templateUrl redirections

I am currently working on developing an Angular application that utilizes $routeProvider. The backend of the application is built using .NET, which serves HTML files tailored with specific permissions and roles for my app. Occasionally, when a certain acti ...

Error: The selectBox function is not defined for $(...)

Currently, I am encountering an issue with the code snippet below when attempting to select options from a dropdown: Uncaught TypeError: $(...).selectBox is not a function. This error message appears in the console. In order to resolve this problem, I ha ...

The DIV element is failing to fill the entire screen's width

I am completely new to web development and currently working on creating my very first website. I've managed to set up the layout, but I'm facing an issue when trying to optimize it for mobile devices. Specifically, some of my divs (particularly ...

"Experiencing a problem with Next.js 13 where the User Context is not functioning properly outside of _app

When using Next.js 13 and the user context, I've noticed that it doesn't function properly outside of _app.tsx. Any idea why? src>context>UserPositionContext.tsx import { createContext, useContext, useState } from "react"; const ...

Access view name in controller using Ui-Router

Utilizing the ui-router in AngularJS allows for the implementation of multiple views within the same page/state. While each view consists of a template, controller, and more, there appears to be no straightforward method of assigning a "resolve" function ...

Unauthenticated user attempting to send a post request via React JS without proper authentication

Currently, I am working on a project where I am following a video tutorial that demonstrates how to authenticate a user using node and passport JS. The tutorial itself uses Hogan JS as its view engine, but I have decided to implement React as my front end ...

Regular expressions to eliminate leading zeros from a string, excluding those that are part of decimals

Looking for a JavaScript regex that can remove any leading 0 in a string if the string is an integer. 0 => '' 0000 => '' 001 => 1 0.11 => 0.11 0000.11 => 0.11 11000 => 11000 I've been attempting to solve t ...

Embark on a journey through a preorder traversal of a Binary Tree using TypeScript

Hello! I've been tasked with creating a function that iterates over a binary tree and returns all its values in pre-order. Here is the code snippet: interface BinTree { root: number; left?: BinTree; right?: BinTree; }; const TreePreArray ...

Pictures in the portfolio failing to load on Mozilla Firefox

Having some trouble with my WordPress website bmfconstruction.com.au/new/. In the project section, all images are loading correctly in Chrome, Opera, and IE. However, when it comes to Firefox, none of the images seem to be showing up. I've tested this ...

The getInitialProps function in Next.js React components does not automatically bind props

When building applications with Next.js, you have the opportunity to leverage a server-side rendering lifecycle method within your React components upon initial loading. I recently attempted to implement this feature following instructions from ZEIT' ...

Adjusting window scrolling on iPad/iPhone based on orientation

When the page loads, I am automatically directing the user's scroll to the top of the '#gallery-view' element. This behavior functions correctly on iPad and iPhone. However, if the device orientation is changed, the positioning does not wor ...

Steps to prevent form submission in AngularJS when input fields are invalid:

Is there a way to disable form submission when incorrect values are entered without using the ng-disabled option? The required option in HTML only checks for empty text boxes upon clicking submit. Do I need to create a custom directive for this task? &l ...

Cross-platform application for Android, iOS, and Amazon Fire TV devices that seamlessly integrates web technology

Is there a platform that supports creating hybrid web apps for Android, iOS, and Amazon Fire TV all in one place? I've been considering Cordova, but I noticed the documentation only covers Android and iOS now. Does anyone know if using Cordova for An ...