Experience the power of live, real-time data-binding for date-time input with AngularFire in 3 different

Here is a simplified version of my code snippet:

tr(ng-repeat='entry in ds3.entries | orderBy:orderByField:reverseSort | filter:query as results')        
    td
      input.screen(type='datetime-local', ng-model='entry.date_received', datetime="MM/dd/yyyy hh:mm a" )
      span(ng-hide='') {{entry.date_received | dateFormat }}
tr.screen
    td
      input.screen(type='datetime-local', ng-model='new_entry.date_received', datetime="MM/dd/yyyy hh:mm a", date-parser="MM/dd/yyyy hh:mm a")
    td
      button.btn-xs.btn-success(ng-click='insert()')
        span.fa.fa-plus-square
        |   Insert

This Jade code segment is used for the HTML view to facilitate adding new datetime-local data and updating it live, similar to a GoogleDocs Excel table.

My goal is to integrate AngularFire (AngularJS 1.x and Firebase database) with this setup. While I've successfully implemented authentication and text input functionality, I'm facing an issue with storing DATETIME values in Firebase. To work around this limitation, I am exploring alternative solutions for real-time editing and manipulation of datetime inputs using 3-way data binding on a collection.

The plan is to send datetime values to Firebase as integer strings (unix_timestamp) and convert them back to datetime format upon retrieval. For this purpose, I have devised two directives.

1- A filter to display the converted result from integer string in the view.

angular.module('workspaceApp')
.filter('dateFormat', ['$moment', function($moment) {
    return function(time) {
      return time ? $moment.unix(time).format('MM/DD/YYYY - hh:mm a') : time;
    };
}])

2- A directive to handle conversion and saving of integer strings to Firebase without displaying errors in the view. This proves challenging due to the complexities of 3-way data binding implementation. For text fields, I simply use ng-change='ds3.entries.$save(entry)' in the input tag.

.directive("input", function () {
return {
    require: 'ngModel',
    /* scope : {
                   entries : "="
    },*/
    link: function (scope, elem, attr, modelCtrl) {
      if (attr['type'] === 'date' || attr['type'] === 'datetime-local') {
        modelCtrl.$formatters.push(function (modelValue) {
          if (modelValue) {
              return new Date(modelValue * 1000);
          } else {
              return null;
          }
        });
        elem.bind('change', function () {
          scope.$apply(function() {
            var str = elem.val();
            var time = new Date(elem.val());
            var unix_time = Math.floor(time.getTime() / 1000);
            console.log(str, unix_time);
            scope.entries.$save().then(function(ref) {
              ref.key() === scope.entry.$id; // true
            }, function(error) {
              console.log("Error:", error);
            });
            modelCtrl.$setViewValue(unix_time.toString());
            modelCtrl.$render();
            // $scope.entry.update(unix_time.toString());
          });
        });
      }
    }
};

})

.directive('fetchDate', function(){
return {
  link: function($scope){
    $scope.$watch('date_received', function(newVal, oldVal){
      if (newVal){
        $scope.entry.date_received = Math.floor(newVal / 1000);
        console.log($scope.entry.date_received);
      }
    });
  }
};

})

I have attempted using ng-change=UpdateFunction() in the datetime input along with corresponding directives and controller functions, but have not yet resolved the issue. Even $watch yielded undefined results for either the old or new date in the console.

$scope.$watch('entry.date_received',function(newVal, oldVal){
  console.log(Math.floor(newVal / 1000) , Math.floor(oldVal / 1000));
  // $scope.update(newVal);
});

If you have any insights or suggestions on how to tackle this problem, please share them!

Answer №1

To enable three-way binding with AngularFire and dates, include this code in your

<input type="date" date-conversion/>
.

app.directive('dateConversion', function () {
return {
    restrict: "A",
    require: "ngModel",
    link(scope, element, attributes, ngModel) {
        ngModel.$formatters.push(value => {
            let output = null;
            if (value) {
                scope.stringValue = value;
            }
            if (value) { output = moment(value).toDate(); }
            return output;
        });

        ngModel.$parsers.push(value => {
            let output = null;
            if (value) { output = moment(value).format(); }
            return output;
        });
    },
}

});

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

Using ngFor directive to iterate through nested objects in Angular

Receiving data from the server: { "12312412": { "id": "12312412", "something": { "54332": { "id": "54332", "nextNode": { "65474&q ...

Reactjs encountering issues loading css file

Currently, I am working on a project in Reactjs with Nextjs. To add CSS to my project, I have stored my CSS files in the 'styles' folder. In order to include them, I created a file called '_document.js' and implemented the following cod ...

The JavaScript array remains unaltered

I've got an express server set up with GET and POST routes. The initial state looks something like this: let orders = [ { sum: 0, purchases: [ { id: 1, contractId: ...

Master the Art of Crafting Unique URLs

I am developing a web page that requires me to call two queries, each requiring an ID. However, I'm unsure of the best way to pass these IDs in the URL. For instance, one query is for books and the other is for authors. Currently, I have considered tw ...

Can data be transferred within a callback to the function it encapsulates?

I am currently working on developing a user login system and I find myself in need of querying the database. Being a beginner in coding, I am grappling with the concept of callbacks and how data can be passed once the callback has been executed. My dilemm ...

AngularJS allows a function to return an array value, which can be displayed in separate blocks on

Building a program that involves working with an AngularJS array. I need to showcase the elements of the AngularJS array, returned by a function, in an organized manner. Each element should be displayed correspondingly - for example, 'first' cont ...

What is preventing comment upvotes from functioning properly? thinkster.io offers tutorials on AngularJS, MEAN stack, and the function incrementUpvote()

Currently, I am working through the Angular JS tutorial provided by thinkster at this link: When attempting to increment the upvote count by clicking on the upvotes icon adjacent to a comment, it fails to execute. Within a ui-router template embedded wit ...

Fix issue with nested form in Rails 3.0.9 where remove_fields and add field link functionalities are not functioning properly

I've been watching Ryan Bates' nested_forms episodes 1 & 2 on RailsCasts, successfully implementing the functionality in one project without any issues. However, in a new project using the same reference, the remove and add field functionalit ...

Ways to adjust the border color when error helper text is displayed on a TextField

I am currently working with React Material UI's TextField element. What I aim to achieve is when the submit button is pressed, the helpertext displayed should be "Please enter the password." It should look like this: However, once the helpertext is ...

Tips for toggling ng-class in AngularJS

My current challenge is toggling classes with ng-class, especially when dealing with tabs that contain sub <a>. Here is the relevant HTML code: <ul class="nav navbar-nav navbar-right"> <li ng-class="{active:isActive('/home')}" ...

Please insert a decimal point and thousand separator into the text field

I'm trying to incorporate thousand separators and decimal points into my text box. Additionally, I have implemented the following directive: .directive('format', function ($filter) { 'use strict'; return { requir ...

How come once I close a PrimeNG modal that is defined within a child component, I am unable to reopen it?

Currently, I am developing an Angular application that utilizes PrimeNG. In the process, I encountered a challenge. Initially, I had a component with a PrimeNG Dialog embedded within (refer to this link), and it was functioning properly. To streamline my ...

Using JQuery validate to extract the interest rate from a regular expression

I am looking for a regular expression that can extract the interest rate. I need it to accept values such as: Examples: 0 0.4 0.44 4 44 4.00 44.00 4.2 4.22 44.22 Minimum value allowed is 0 and maximum is 99.99 The regular expression should be ab ...

Troubleshooting issue with JavaScript sorting function failing to arrange elements in ascending

I'm having trouble sorting numbers in ascending order using JavaScript. Here's the code snippet: <h2>JavaScript Array Sort</h2> <p>Click the button to sort the array in ascending order.</p> <button onclick="myFunctio ...

AngularJS integration with Bootstrap Confirmation jQuery plugin

I am currently struggling to implement the Bootstrap-Confirmation plugin with AngularJS. Despite following instructions from this YouTube tutorial, I cannot seem to get the directive to function correctly. A related query on Stack Overflow references a di ...

Is there a way to show a loading icon during the image change process without using jQuery?

How can I add a loading icon to an image change event without using jQuery? I'm new to the coding world and Stack Overflow community, so please bear with me. I've been searching for a solution to my specific situation but haven't been able ...

A thrilling twist on the classic game of Tic Tac Toe, where X and

I am having trouble with switching between the cross and circle symbols in my Tic Tac Toe game. The code seems to be set up correctly, but it's not functioning as expected. Any suggestions on how to fix this? Here is the JavaScript code: varcode va ...

The $http patch request is failing to transmit data to the server

Recently, I started utilizing AngularJS to create a CRUD functionality using Laravel and AngularJS. I have implemented a function that serves the purpose of both updating and saving data. Here is my function code: $scope.save = function (modalstate, id) ...

Is it possible to clear a div using jQuery and then restore its contents?

In my setup, I have a video player within a div where clicking the play button (.video-play-container) fades in the video, and clicking the close button (.close-video) fades it out. The issue arose when the faded-out video continued playing in the backgr ...

What is the best approach to accumulate model data in an Angular JS service or controller through a series of consecutive calls?

I am facing a challenge where I need to display the results of multiple REST server calls on a single page using AngularJS. The initial call retrieves details about a specific product, including the IDs of other related products. My goal is to not only s ...