Is it acceptable to utilize $$updated while expanding a firebase factory in order to execute a getTotal() method similar to the one demonstrated in the example

Is there a way for me to retrieve the data returned by $$updated or have $$updated trigger a function that I can then receive every time a task is marked as completed?

By the end of the day, I need to maintain a count of how many tasks users have finished. It appears that firebase offers methods for automatically syncing this data, but the specifics on how to achieve this are unclear to me. I've encountered issues with $watch and executing functions upon task completion. The approach outlined here seems promising, but I'm struggling to connect all the pieces together.

Check out a working plnkr of the code here: http://plnkr.co/edit/iAGvPHFWn2GSPGzBRpKh?p=preview

// Code goes here
angular.module('app', ['firebase']);

angular
  .module('app')
  .controller('main', function($scope, $firebase, $timeout, $window, ListWithTotal) {

  var ref = new Firebase("https://plnkr.firebaseio.com");
  $scope.listWithTotal = ListWithTotal(ref);

  $scope.addTask = function(task) {  
    $scope.listWithTotal.$add({
      title: task.title,
      complete: false,  
      tally: 0  
    });
    task.title = ''; 
  };

  $scope.completeTask = function(task) {  
    if (task.complete === true) {
      task.complete = true;
      task.tally = 1;
    } else { 
      task.complete = false;
      task.tally = 0;
    }
    $scope.listWithTotal.$save(task);
  };

  $scope.tallyCount = '';
  //it would be cool if I can get tallyCount to receive 
  //the result of getTotal or automagically with $$updated. 


}).factory("ListWithTotal", ["$FirebaseArray", "$firebase", function($FirebaseArray, $firebase) {
  // create a new factory based on $FirebaseArray
  var TotalFactory = $FirebaseArray.$extendFactory({
    getTotal: function() {
      var total = 0;
      angular.forEach(this.$list, function(rec) {
        total += rec.tally;
      });
      return total;
    },
    $$updated: function(){
      return this.$list.getTotal();
    }
  });
  return function(listRef) {
    var sync = $firebase(listRef, {arrayFactory: TotalFactory});
    return sync.$asArray(); // this will be an instance of TotalFactory
  };
}]);

Answer №1

To receive an updated count of all tasks that have been finished, simply include a then statement at the point where you are saving the task:

$scope.completeTask.$save(task).then(function() {
  $scope.totalCompletedTasks = $scope.completeTask.getCount();
});

Once the task has been saved, the then block will execute and update the current scope with the total count of completed tasks.

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

Modifications performed on the Xhtml generated from xml and XSLT should be mirrored back into the original XML document

After transforming an XML file with xsl and loading it into a browser as html, I am making the html editable using the content editable attribute of html5. How can I transform their edits back to the original xml document, even if they add new nodes to e ...

fetching indexeddb information using the equivalent of a "WHERE IN (a,b)" query

I've been working on transitioning from websql to indexeddb, but I'm struggling to recreate the SELECT query: "SELECT * FROM tableA WHERE cid ='"+cid+"' AND hid IN("+hid+",1) ORDER BY hid DESC LIMIT 1"; function getMyData(e) { var ...

When using @Html.ActionLink in ASP.NET MVC-5, the URL in the address bar may change, but the page does not redirect to the destination

I am experiencing an issue with my MVC view where different Angular views are displayed based on a condition. However, once the Angular views are loaded, none of the links on the MVC page seem to be working. When I click on a link in the MVC view, the addr ...

Interacting with the header component within the renderHeader property of the MUI Data Grid Pro will update the sortModel

Currently, I am utilizing the Material UI DataGridPro component to construct a React Js application. I am interested in developing a customized filtering feature. In the image below, you can see a red box representing an IconButton for the filtering view ...

Sorting in reverse order within a table

Is there a way to reverse the order in which my function renders table rows with incremental id? (first row with id=n, last with 1) Here is the code snippet I am using: renderRows = () => { const { receipts } = this.props const reversedReceipt ...

Can you define the type of binding value in AngularJS 1.5(6) using TypeScript?

I am looking to define the type of binding items so that I am able to utilize components similar to functions. For instance, consider a component: angular.module('app').component('navBar', new NavBar()); class NavBar{ public bin ...

Error in Asp.Net Mvc Bundle: Incorrect Path for Scripts

In my ASP. NET MVC Project, I have set up BundleConfig to include jquery, bootstrap, and modernizr scripts. Everything works well when running locally, with the path leading to the exact .js file. However, when I publish the project to the hosting server, ...

Show the HTML code within the form with the identifier html-editor-form

I have four different sections which are displayed when the corresponding icon is clicked. The area labeled as visual-editor contains multiple HTML values. I am looking to showcase all the HTML values within the visual-editor class under the html-editor ...

Transferring variables from the $(document).ready(function(){}) to the $(window).load(function(){} allows for seamless and

Just think about if I successfully create percent_pass at the time of document.ready, how can I transfer that variable to window.load? $(document).ready(function() { jQuery(function() { var ques_count = $('.question-body').length; va ...

Error encountered in Firefox: THREE.js throws a TypeError because 'global' is undefined

After attempting to integrate three.js into my code as a standalone script without using webpack, browserify or requirejs, I encountered an issue. My setup involves loading an external Angular app and extending it, but now I need my own version of THREE.js ...

Refresh a div using jQuery and include PHP files for dynamic content updating

This is the code I am using to dynamically update divs containing PHP files: $(document).ready(function() { setInterval(function() { $('#ContentLeft').load('live_stats1.php').fadeIn("slow"); $('#ContentRight').load( ...

Cypress, encountering issues with If/Else or Switch Case implementations

My current challenge involves adding else if / switch case in my test. The issue I am facing is that when the initial 'if' condition fails, it does not go into the else if statement. This problem persists in both else if statements and switch cas ...

Eliminate the navigation bar option from a website template

Is there a way to permanently eliminate the menu button in this theme? Any guidance would be appreciated. Here's the link to the theme: https://github.com/vvalchev/creative-theme-jekyll-new ...

Switch between Coordinated Universal Time and a designated time zone using the New Internationalization API

I am experimenting with the new Internationalization API using Chrome Version 31.0.1623.0 canary. My goal is to: Convert Date Time between UTC and a specific time zone (America/New_York as an example). Determine if the conversion takes into account Dayl ...

Display the count of ng-repeat items beyond its scope

Currently, I am looping through a list of nested JSON objects in this manner: <div ng-repeat='item in items'> <ul> <li ng-repeat='specific in item'>{{specific}}</li> </ul> </div> I want to ...

Error: Your Discord bot is unable to send a message as it is empty. Please check Discord

I have been developing a Discord Bot to verify Roblox accounts. Although my script is prepared and the command "-verify" can be executed, an error arises: (node:22872) DeprecationWarning: The message event is deprecated. Use messageCreate instead (Use `n ...

Verifying that every API has been successfully loaded on a page in AngularJS

In my AngularJS application, I am using 4 controllers on a single page. Each controller makes API calls using the $http service. I need a way to confirm that all the APIs have been successfully called and loaded before displaying the loading GIF image. H ...

Exploring the capabilities of Redux Toolkit's createEntityAdapter in designing versatile data grids

Seeking guidance on utilizing createEntityAdapter from Redux Toolkit. In my application, I display package information and details using the master/detail feature of the AG Grid library. Packages are loaded initially, followed by fetching detailed data as ...

Structure of Django, Nginx, Gunicorn, and AngularJS Application

Important: I have reviewed the answers provided in links like Serving static files with Nginx + Gunicorn + Django & How exactly do I server static files with nginx and gunicorn for a Django app? I am currently working with Django and AngularJS, and ha ...

Encapsulating data with JSON.stringify

I'm currently working on creating an object that has the following structure: let outputOut = { "_id": id[i], "regNum": code[i], "sd": sd[i], "pd": ptOut, "p": p[i], ...} //output fs.writeFile('./output/file.json', JSON ...