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

The Angular filter is failing to display the category value

My issue lies in adding a filter to display categories, as my setCurrentCategory function is not showing any value but instead displaying 'undefined'. The goal is to show the category for each person. I'm using ng-click to pass to my functio ...

"Exploring the process of assigning input data to a different variable within a Vue component

Reviewing the code snippet I currently have: <template> <div> <input v-model.number="money"> <p>{{ money }}</p> </div> </template> <script> name: 'MyComponent', data () { ...

The error stating that document.getElementById(...) is null has occurred within RSForms due to a TypeError

Issue: When clicking on the form to continue, a TypeError: document.getElementById(...) is null error occurs. Can anyone help me fix this problem? When I click on the continue button, it calls the function submitForm. <script type="text/javascript"> ...

jQuery Ajax allows scripts to be contained within a page, even if the page itself is empty

Utilizing jQuery ajax to display an HTML page that includes javascript functions, here is my code: function ChartBook() { $.ajax({ url: '/Charts/ChartBook', dataType: 'html', id: 1, ...

How can Jquery detect when users click on 'ok' in confirm() pop-up dialogs?

Within my application, I have multiple confirmation dialogues that appear when users attempt to delete certain items. Is there a method to determine if a user has clicked the 'ok' button on any of these dialogues globally so that I can execute a ...

Creating a customized post method in Angular's resource API

I am looking to streamline my code for posting data to a SharePoint list by utilizing a resource factory. Currently, I have been posting data using the following method: this.save = function(data) { data["__metadata"] = { "type": getItemTypeForListNam ...

Toggle the state of a Material UI checkbox in ReactJS based on the data from hooks that return a true or checked value

I need assistance with checking/unchecking a checkbox value in an edit modal based on the return of addAdvisory(hooks) which is 'Y', indicating true/checked. Below is my basic code snippet: const [addAdvisory, setaddAdvisory] = useState({ SY ...

Run C# script with the assistance of .load jquery

I have searched extensively for similar posts, but none seem to address the specific question I have regarding my project. What I am attempting to do is load different pages (.aspx) in an iframe dynamically. However, instead of using an iframe, I want to r ...

The Algolia Hit Component is having difficulty functioning properly within a grid layout

I am in the process of converting my next API to an Algolia search. The Hit component is a single component that renders for each record. However, I am facing an issue with implementing a grid layout. Below is the code snippet from before (which was workin ...

How to align an image in the center of a circular flex container

I'm facing an issue in my Angular project where I have the following code snippet: onChange(event: any) { var reader = new FileReader(); reader.onload = (event: any) => { this.url = event.target.result; }; reader.readAsData ...

Transmit HTML message using the "textarea" tag through email

Whenever I try to send the content of my "textarea" via email, it always ends up being sent as a blank message. How can I fix this issue? Below is my PHP code: <?php $input = json_decode(file_get_contents("php://input"), true); $ToEmail = "<a href ...

Show a success message, clear the post data, and redirect back to the current page

I have a single web page with a contact form. When the form is submitted, I want it to redirect to the same page and display a success message that fades out after a few seconds. Additionally, I want the post data of the form to be cleared. The form also i ...

What is the best way to utilize $emit in order to postpone the execution of a function for the following minute?

Within my service code, I have the following snippet: $rootScope.$emit('rootScope:success-response') Additionally, there is a function that runs every 60 seconds in another part of the code: this.$interval(function () { myFunc() ...

JavaScript prototypal inheritance concept

During my free time, I like to dabble in JavaScript, but I’m currently struggling with this particular topic. var person = new Person("Bob", "Smith", 52); var teacher = new Teacher("Adam", "Greff", 209); function Humans(firstName, lastName) { this. ...

Leverage scope variables and dynamic CSS properties when using ngClass

Is there a way to manipulate the CSS dynamically in HTML using a scope variable? <div ng-class="myClassScope, { 'dynamic-class': !ifIsNot }"> ...

What causes z-index to be ineffective with sticky elements?

In my website, I've implemented rollover effects in a sticky footer and a responsive menu that stays at the top. However, when the menu is opened and extends over the footer, it covers everything except the rollovers. Closed navigation http://www.mus ...

Is a UI routing race problem a concern?

After some observation, I've identified a potential race condition that occurs when switching between states too quickly. For example, let's say I navigate to state A. The directives linked to this state are compiled. This process could take lon ...

"Enhancing JqGrid functionality with inline editing and custom formatters

I'm currently working with a column model that looks like this: { name: 'CostShare', index: 'CostShare', width: 50, formatter: 'number', formatoptions: { decimalPlaces: 2, suffix: "%" }, resizeable: true, align: 'ce ...

Unlocking the parent scope in a custom attribute directive

I am new to utilizing angular js. I came across a similar inquiry on How to access parent scope from within a custom directive *with own scope* in AngularJS? However, the solution provided did not work for my basic test. Here is the sandbox. http://jsfi ...

Handling 404 Response from WebAPI in $Http.get() Function

While using my web application, I am executing a GET command to access a remote HTTP WebAPI service. $http.get(url).then(function(data) { do_something(); }); When the WebAPI successfully returns data, everything functions as expected. However, in cases w ...