The 3-way data binding in angularFire does not update a function

My issue involves a firebaseObject (MyFirebaseService.getCurrentUser()) being bound to $scope.user. Once successfully bound, I iterate through the object to check if it contains an "associatedCourseId" equal to a specific value ($stateParams.id). If it does, the $scope.finishLessonCount increases. The problem arises when I add a new Object to the firebaseObject (bound to user) from another page or within firebase itself, as the finishLessonCount value does not update as expected with 3-way binding. I have to refresh the page in order to see the finishLessonCount reflect the correct value. I want the finishLessonCount to change automatically using the compare function whenever more finishedLessons are added to the firebaseObject. Here is my code snippet:

MyFirebaseService.getCurrentUser().$bindTo($scope, "user").then(function(){

        for (var key in $scope.user.finishedLessons) {
            if ($scope.user.finishedLessons.hasOwnProperty(key)) {

                if ($scope.user.finishedLessons[key].associatedCourseId == $stateParams.id) {
                    $scope.finishLessonCount++;
                }
            }
        };
        console.log ($scope.finishLessonCount);
    });

UPDATE 1 based on @Kato's suggestion: I attempted to resolve this issue by extending the firebaseObject method, but unfortunately that did not work either. To simplify and avoid using factory, I needed to pass in the courseId for the operation. Below is the updated code:

       function countLessons(lessons, courseId) {
       var count = 0;
       for(var key in lessons) {
          if( lessons[key].associatedCourseId ==  courseId) {
             count++;
          }
       }
       return count;
    }

    var UserWithLessonsCounter = $firebaseObject.$extend({
      $$updated: function(snap) {
         var changed = $firebaseObject.prototype.$$updated.call(this, snap);
         this.lessonCount = countLessons(this.finishedLessons, $stateParams.id);
      }
    });

    var refTemp = new Firebase($rootScope.baseUrl + "users/" + $rootScope.userId);
    var userTemp = new UserWithLessonsCounter(refTemp);

    userTemp.$bindTo($scope, "userTemp").then(function(){
        console.log($scope.userTemp);
    });
    userTemp.$watch(function() {
      console.log("Does this run at all? " + $scope.userTemp.lessonCount);
   });

Even after updating the user object, the lessonCount value remains unchanged unless I refresh the page. Additionally, the console.log statement inside the $watch function does not execute at all. What could be causing this issue?

Answer №1

The $bindTo function returns a promise that is executed only once. It should not be mistaken for an event listener, as it does not provide real-time updates.

For a better understanding of how to handle data changes in Angular, it is recommended to read the guide and familiarize yourself with Angular's $watch method before proceeding further.

If you are new to Angular, consider using the $watch function:

Example: MyFirebaseService.getCurrentUser().$bindTo($scope, "user");

$scope.$watch('user', function() {
   for (var key in $scope.user.finishedLessons) {
      if ($scope.user.finishedLessons.hasOwnProperty(key)) {
        if ($scope.user.finishedLessons[key].associatedCourseId == $stateParams.id) {
          $scope.finishLessonCount++;
        }
      }
   };
   console.log ($scope.finishLessonCount);
});

Alternatively, after studying the AngularFire API, one may opt for $scope.user.$watch() for improved efficiency.

To streamline the process, one could utilize the $extend tool within AngularFire for scenarios like this:

// code example utilizing $extend
app.factory('UserWithLessonsCounter', function($firebaseObject) {
   return $firebaseObject.$extend({
      $$updated: function(snap) {
         var changed = $firebaseObject.prototype.$$updated.call(this, snap);
         this.lessonCount = countLessons(this.finishedLessons);
         return changed;
      }
   });
});

function countLessons(lessons) {
   var count = 0;
   for(var key in lessons) {
      if( lessons.hasOwnProperty(key) ) {
         count++;
      }
   }
   return count;
}

In the controller:

app.controller('...', function($scope, UserWithLessonsCounter) {
   var ref = new Firebase(...);
   var user = new UserWithLessonCounter(ref);
   user.$bindTo($scope, 'user');

   user.$watch(function() {
      console.log($scope.user.lessonCount);
   });
});

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

Setting up a search bar using Datatable within a MEAN stack environment

How can I optimize the search functionality for a table loaded from MongoDB through a Controller in the MEAN architecture (MongoDB, Express, Angular, NodeJS)? On my main page: <section class="content"> <div class="nav-tabs-custom" ng-controller= ...

When the user clicks, the template data should be displayed on the current page

I need help with rendering data from a template on the same HTML page. I want to hide the data when the back button is clicked and show it when the view button is clicked. Here is my code: <h2>Saved Deals</h2> <p>This includes deals wh ...

What is the method for triggering a JavaScript function by clicking a button within a CakePHP application?

<button type="button" id="addleetdata" class="btn btn-primary addleetdata float-left">Add</button> JS File $("#addleetdata").click(function () { console.log("entering into function") startLoading(); console.log("editin ...

Tips for incorporating Firebase Timestamp when inserting an item from a data class into Firestore using Kotlin

In this snippet, I am showcasing my data class structure for adding product details to the Firestore. My aim is to incorporate a Firebase timestamp to track when the item is added. However, I am facing challenges in implementing this feature, as my attempt ...

How to incorporate a JavaScript file into a Handlebars template

I am having trouble receiving calls to my JavaScript file. What could be the issue? Using MVC. Here is the code in view file, file.hbs: <div class="container"> <h2 onClick="test()">Title</h2> {{>list}} </div> <script sr ...

Load the React component asynchronously while waiting for the data to be fetched

My ReactJS component looks like this: import React, {useState} from 'react'; import Plot from 'react-plotly.js'; import {utility} from "./utility"; function Chart() { const [use_data, setData] = useState([]); c ...

Node.js: Extracting parameters from the URL

When working with Rails, I make a POST request to my server: response = Typhoeus::Request.post("http://url.localtunnel.com/request?from=ola&to=ole") result = JSON.parse(response.body) Now in my Node.js application, I need to retrieve values for From ...

Retrieve the name of the product from the corresponding parent element

My goal is to trigger an alert box with the product name when the "Buy now" button is clicked. I have added the necessary code in jquery to maintain the onclick event of the button. <h2 class="product-name"><a href="product1.php" title="Sample Pr ...

Content briefly appears and then vanishes with the use of ng-if

On my webpage, I have content that is enclosed in an ng-if directive as shown below: <div ng-if="ShowMessgae" class="text-danger"> <p> <strong> Message displayed to User </strong> </p> < ...

Attempting to transpile JavaScript or TypeScript files for compatibility within a Node environment

Our node environment requires that our JavaScript files undergo Babel processing. Figuring out how to handle this has been manageable. The challenge lies in the fact that we have a mix of file types including .js, .jsx, .ts, and .tsx, which is not subject ...

Exploring the attributes used in AngularJS directives

I have been exploring AngularJS and noticed that it introduces unique attributes that do not follow the standard HTML attribute format, such as: <html ng-app> or <body ng-controller="PhoneListCtrl"> Where do these ng-* attributes originate ...

Troubleshooting NodeJS and Express: Issue accessing a function located outside a folder

I'm having trouble accessing the function I exported in app.js Here is the code snippet from app.js: function getConnection() { return mysql.createPool({ host: 'localhost', user: 'root', password: &apo ...

methods for transferring information from a website to a smartphone using SMS

I am currently in the early stages of learning JavaScript and working on a project that involves creating a form (a web page) to send data to my mobile device via SMS when the submit button is clicked. However, I am unsure how to transfer data from JavaS ...

invoke two JavaScript functions without displaying any message

I'm facing an issue with Ajax as it's not displaying the message I intend to show. Let me elaborate. Within my PHP code, there is an input tag: <input type="submit" id="login_button_add" name="submit" value="Add" onclick="add_building(); sho ...

Application Layer Capability

I am currently in the process of developing an App that requires authentication. To ensure that the user is authenticated before changing routes and instantiating the route Controller, I need to implement a function that can retrieve the logged-in user fro ...

Enhancing Website Interactivity with PHP, AJAX, and

I recently followed a tutorial on handling AJAX requests with PHP and MySQL, which can be found here. My goal is to update the SQL query based on the value selected from a dropdown menu using the onchange event. function myfunctionTime(time) { if (t ...

Using Javascript to create a new regular expression, we can now read patterns in from

I am currently working on developing a bbcode filtering solution that is compatible with both PHP and JavaScript. Primarily focusing on the JavaScript aspect at the moment, I have encountered an issue with the new RegExp constructor not recognizing pattern ...

Difficulty establishing a connection between data in app.js and index.html using Ionic framework

Struggling with connecting index.html to get data for my Ionic mobile app. Any tips or guidance would be highly appreciated as I'm new to this! The goal is to display a list of restaurants in the app, utilizing Cards Images to showcase an image, logo ...

Receive JSON data with camel-case in a Web API 2.0 using a model in pascal-case style

My attempt to execute a PUT call on my Web API involves configuring the WebApiConfig.cs file to send data back to my Web project in camel case format. config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesCont ...

Error: The function seems to be malfunctioning or missing

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $('div'); // <--- THIS DOESN'T WORK </script> An issue has been encountere ...