Enhance your Angularfire experience with $firebaseArray by enabling dynamic counting and summing

Is there a way to dynamically count certain nodes if they are defined?

The current implementation requires explicitly calling sum().

app.factory("ArrayWithSum", function($firebaseArray) {
  return $firebaseArray.$extend({
    sum: function() {
       var total = 0;
       var todayDate = new Date();
       var start = todayDate.setHours(0,0,0,0);
       var end = todayDate.setHours(23,59,59,999);

        // the array data is located in this.$list
        angular.forEach(this.$list, function(rec) {
            if (angular.isDefined(rec.qa)){
                if (angular.isDefined(rec.qa.completed)) {
                    if (rec.qa.completed >= start && rec.qa.completed <= end){
                        total++;
                    }
                }
            }

        });
        return total;
    }
  });
});

I attempted to use $$update but encountered issues accessing this_counter within the array:

  app.factory("counter", function($firebaseArray) {
      return $firebaseArray.$extend({
        sum: function() {
            return this._counter;
        },
        $$updated: function(){

           var changed = $firebaseArray.prototype.$$updated.apply(this, arguments);

           var todayDate = new Date();
           var start = todayDate.setHours(0,0,0,0);
           var end = todayDate.setHours(23,59,59,999);

           if( !this._counter ) { 
               this._counter = 0; 
           }

            // the array data is located in this.$list
            angular.forEach(this.$list, function(rec) {
                if (angular.isDefined(rec.qa)){
                    if (angular.isDefined(rec.qa.completed)) {
                        if (rec.qa.completed >= start && rec.qa.completed <= end){
                            this._counter++;
                        }
                    }
                }

            });
          return changed;
        }
      });
    });

Any insights on creating a dynamic variable that can be updated and accessed would be greatly appreciated.

Thank you!

Answer №1

Successfully implemented $firebaseObject to incorporate a property _counter into an object, rather than an array. This method proves to be effective in obtaining a dynamic count.

app.factory("counter", function($firebaseObject) {
  return $firebaseObject.$extend({
    $$updated: function(){

       var changed = $firebaseObject.prototype.$$updated.apply(this, arguments);

       if( !this._counter ) { this._counter = 0; }

       var total = 0;
       var todayDate = new Date();
       var start = todayDate.setHours(0,0,0,0);
       var end = todayDate.setHours(23,59,59,999);

        // the array data is located in this.$list
        angular.forEach(this, function(rec) {
            if (angular.isDefined(rec.qa)){
                if (angular.isDefined(rec.qa.completed)) {
                    if (rec.qa.completed >= start && rec.qa.completed <= end){
                        total++;
                    }
                }
            }

        });

      this._counter = total;
      return changed;
    }
  });
});


vm.panels = new counter(panelsRef);

{{vm.panels._counter}}

Facing challenges with watches not triggering after an extended period on IE11. Hence, exploring this alternative approach.

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

Can a client component in NextJs retrieve data from a server component?

Apologies for the way the question is phrased. I have a server component named auth.ts that retrieves user details after they log in. This server side component is located at //auth.ts export const validateRequest = cache( async (): Promise< { use ...

After reloading the data tables, analyze the information and dynamically highlight any rows in red that remain unchanged

I have a table that is refreshed every 5 minutes using ajax.reload(). One of the rows in this table is labeled as CIP. My goal is to highlight the CIP row on each refresh where the value remains unchanged from the previous value (value received in the la ...

Toggle visibility on the child DOM element of each item in the v-for loop

Here's an example of a template: <template> <table class="table table-hover"> <tbody> <tr> <th style="width:260px">Info</th> <th>Deta ...

What is the best way to transform this unfamiliar CSS element into JavaScript code?

I'm facing an issue where I want to animate a CSS image based on time constraints, but since it's in CSS, I'm unable to achieve the desired effect. The animation in question is not the sun itself, but rather a yellowish half-circle animation ...

Managing events with classes

I have multiple divs with the same class. When one of these divs is clicked, I want to change the display of the other divs to 'block'. Currently, I am using inline JavaScript for this functionality, but I would like to achieve it without inline ...

Tips for validating a receipt in an In-App purchase within an Ionic1 or Ionic2 application on iOS

Currently, I am working on integrating InApp purchases into an iOS app built with Ionic. However, I am facing difficulties in validating the receipt. Despite successfully obtaining the transaction ID and receipt post-purchase. ...

What is the best way to send a string from an HTML form, route it through a router, and create and save an object?

Currently, I am facing an issue while attempting to transfer a string from the frontend to the backend. The technologies I am using include Node, Express, Body Parser, EJS, and PostgreSQL. Here is the basic structure of my file system: – app |– api ...

utilize ng-include in angularjs to include a page

For some reason, I am having trouble including a file using ng-include. The file is supposed to be included when a button is pressed: <button type="submit" class="btn btn-primary" ng-click="getPartial()">Compare</button> This is the function ...

Error-free ngClick doesn't trigger AngularJS controller method

I am struggling to trigger the removePlayer(playerId) method upon clicking a button. However, it seems that the method is not being called, as I have placed a console.log() statement at the top and the console remains empty. This situation has left me puz ...

The MyFunction method in the Typescript Class.prototype is experiencing issues, but is still

It's puzzling why I encounter an error even though the code functions properly. Could this be a bug in the compiler? (I am using Visual Studio Code with Angular 2) class A { fun(a: number) { return a+2; } } A.prototype.F = funct ...

Does Three.js come with a default function for generating heightmaps?

Currently, I am engrossed in developing a JavaScript game using Three.js. My interest lies in enhancing the realism of the walls by incorporating a height map (refer to the provided image). View this snapshot of the game design featuring a 2D wall. All th ...

Stop Internet Explorer from automatically scrolling when it gains focus

Please access this fiddle using internet explorer (11): https://jsfiddle.net/kaljak/yw7Lc1aw/1/ When the page loads, the <p> tag is focused and Internet Explorer slightly scrolls the element so that the table border becomes invisible... document.qu ...

Why Bootstrap 4 collapse feature is not functioning correctly within a ReactJS map component?

I am currently working on a project that requires implementing a collapse feature. The idea is to display all available content when the user clicks the Read More button (which is functioning as intended for collapsing). However, I am facing an issue where ...

What is the best way to save String arrays to a text file in Java with the help of PrintWriter?

Looking for assistance in writing the contents of array objects to a text file using Printwriter. I'm a beginner, so any simple ideas would be greatly appreciated! Astronauts[0][0] = new Passengers(-1, "", 1, 0, 0, "", "", 0, "", "", "", "", ""); ...

developing a dropdown menu feature

I'm struggling with a small issue related to my drop-down menu function. My goal is to hide the visibility of a menu tab after it has been clicked for the second time. Below is the code snippet I've been working on: HTML:- <nav class="clea ...

Eliminating clutter in bespoke event handlers - eliminating the necessity for the 'event' parameter

I have a project where I am creating objects that will trigger custom events, and I am using jQuery's bind and trigger functions to handle this task. Here is an example of how I am implementing it: function MyObject() { var _this = this; th ...

Tips for implementing orderBy and filter in ng-repeat when working with an object instead of an array

I am facing a data structure that looks like this: $scope.people = { "ID123": { name_de: "Andre", name_en: "Anrew", age: 30, description: "He is the father of xyz and . . .", . . . ...

Issue with AngularJs failing to display data

As a newcomer to AngularJS, I am looking to utilize AngularJs to display the Json output from my MVC controller. Here is the code snippet for my MVC Controller that generates Json: [HttpGet] public JsonResult GetAllData() { ...

The Discord.js script fails to send embedded messages as intended

Issue with sending embedded messages using Discord.js code Embed code not functioning properly: Error code received: ...

What steps can be taken to deter users from repeatedly liking comments, similar to the systems seen on Facebook or YouTube for like/dislike features?

I am currently working with express, react, and MySQL. My goal is to implement a like/dislike system for comments. After doing some research, I found that many suggest disabling the like button after a single click. However, I want users to be able to se ...