Converting Dates to getTime() in AngularJS prior to server transmission

In my form, I am using

<input type="datetime-local" ng-bind="course.endDate"..
to set a model variable. Before sending the date to the server, I need to convert the date 2015-04-04T22:00:00.000Z to an integer using getTime().

In the controller, I added the following code:

course.endDate = course.endDate.getTime();
. While this works for the server side, Angular throws an error in the console which can be seen here. (Although it works, I want to prevent errors)

Error: [ngModel:datefmt] Expected `1325458800000` to be a date
http://errors.angularjs.org/1.3.15/ngModel/datefmt?p0=1325458800000
    at REGEX_STRING_REGEXP (angular.js:63)
    at Array.<anonymous> (angular.js:19938)
    at Object.ngModelWatch (angular.js:23419)
    at Scope.$get.Scope.$digest (angular.js:14300)
    at Scope.$get.Scope.$apply (angular.js:14571)
    at done (angular.js:9698)
    at completeRequest (angular.js:9888)
    at XMLHttpRequest.requestLoaded (angular.js:9829)

How can I resolve this issue?

I had the idea of adding some fields in the form (formEndDate) and converting it to another field (endDate = formEndDate.getTime()) for the server side. However, this approach leads to the server rejecting the call since the parameter formEndDate is not allowed, and removing the formEndDate breaks everything.

Additional Problem: When I retrieve data from the server, I have an integer that needs to be converted into a date for use in the form. I must convert the date before enabling editing. Is there a way to accomplish this without iterating over the entire array of fetched data?

Solution

Thanks to the helpful responses, I have managed to solve the issue with the form when editing. I created an additional field to use when editing the form (I utilize inline editing).

I have shared a gist here

Answer №1

Prior to transmitting the information to the server, create a duplicate and update the endDate field. Afterwards, send the duplicate to the server:

var courseCopy = angular.copy(course);
courseCopy.endDate = courseCopy.endDate.getTime();

Answer №2

When working with Angular, it is recommended to store all form data within a single property, such as:

$scope.formData = { endDate: 'xxx', ... };

Prior to sending the data to the server, it is important to create a duplicate of the formData:

var formDataCopy = angular.copy($scope.formData);

This allows you to perform any necessary transformation operations on the duplicate without affecting the original data in your scope.

Answer №3

To alter the request's body, utilize the transformRequest function, as demonstrated in this code snippet sourced from the official AngularJS documentation:

function addTransformation(defaults, transformation) {
  // Cannot assume defaults is an array
  defaults = angular.isArray(defaults) ? defaults : [defaults];

  // Add the new transformation to defaults
  return defaults.concat(transformation);
}

$http({
  url: '...',
  method: 'GET',
  transformRequest: addTransformation($http.defaults.transformRequest, function(value) {
    // Implement payload transformation here
    return value;
  }),
  transformResponse: addTransformation($http.defaults.transformResponse, function(value) {
    // Implement response transformation here
    return value;
  })
});

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

What are the steps to implementing a JavaScript WebWorker in a webpack environment?

Struggling to implement web workers in my web app and encountering difficulties. The addition of a new entry to the webpack.config.js file is not producing desired results. Attempting to utilize the npm package named worker-loader, however, facing challen ...

Deactivate the ability to hold a button, but still permit clicking in HTML for mobile

I am currently developing a progressive web app for mobile devices. One feature I have implemented is the ability for users to long-press a button with their finger, triggering a popup menu that includes options like "copy link address," "copy text," and " ...

What is the abbreviated term for personalized elements in React Native development?

After discovering that custom components can be created like this: const CustomComp=()=>{ console.log('Created custom comp'); return(<View></View>); } export default function App(){ return(<View style={{flex:1}}> &l ...

There seems to be this strange and unexpected sharing of Animated.View and useRef between different child components

Currently, I am displaying a list of items in the following manner: {formattedJournal[meal].map((food, idx, arr) => { const isLast = idx === arr.length - 1; return ( <View key={idx}> ...

Decoding JSON in AngularJS

Looking for assistance in parsing a JSON 2D array with Angular JS and fetching images from the array. Can anyone provide some guidance on this? I have updated my Plunker at this link HTML Code <!DOCTYPE html> <html lang="en" ng-app="myAp ...

Load images in advance using jQuery to ensure they are cached and retrieve their original sizes before other activities can proceed

When a user clicks on a thumbnail, I aim to display the full-size image in a div. To achieve this, I want to determine the original size of the image based on its source URL before it loads, allowing me to set the appropriate dimensions for the container. ...

Using Bootstrap's nav-pills inside a table

Is there a way to incorporate Bootstrap Nav Pills into a table, with the "tab buttons" located in the last row of the table? I've attempted it but it doesn't seem to be functioning correctly. Check out this link for reference <table clas ...

When using jquery.hide() and show(), the content within the div disappears momentarily before reappearing

Hello! I am experiencing an issue where the content of my div disappears after using a jQuery hide() and show() function. It seems to be gone. <li class="gg3"><a class="link" href="#" data-rel="content3">Link1</a></li> <div clas ...

Enhancing the appearance of individual cells in jQuery DataTables

While working with jQuery DataTables, I have successfully managed to access row data and apply styling to the entire row. Below is the code snippet used to initialize the datatable: var $dataTable = $('#example1').DataTable({ "data": data, ...

What causes the .getJSON function to return a MIME type error when trying to access the API

I've been attempting to make a call to the Forismatic API, but I keep encountering a MIME type error when sending it. JQuery Request: $(document).ready(function() { $("#quote-button").on("click", function(){ $.getJSON("https://api.forism ...

What is the best way to turn my thumbnail into a clickable link while having the title positioned to the right?

Is there a way to create a thumbnail that acts as a link and position the title next to the thumbnail? I have experimented with using 'after' and modifying the HTML structure to align them horizontally. Any ideas on how I can achieve this layou ...

What is the best way to generate a complete PDF of a webpage using pdfmake?

I'm currently developing a web application and facing the task of converting an HTML page, which contains multiple tables and datatables, to a PDF format. To achieve this, I've chosen to utilize the library pdfmake. Below is the script that I ha ...

Tips for organizing your JSON Structure within ReactJs

In the given example, I have a JSON structure with information about different airlines. The Airline Name is dynamic and we need to separate the JSON into an expected array format. const arr = [ { Airline: "Goair", Departure: "01:50" ...

Translate data from two "contact form 7" date fields into JavaScript/jQuery to display the date range between them

NEW UPDATE: I was able to get it working, but the code is a bit messy. If anyone can help me clean it up, I would greatly appreciate it. <div class="column one-fourth" id="date-start">[date* date-start date-format:dd/mm/yy min:today+1days placeholde ...

What is the best way to guide a user to a specific page based on the choice they made after submitting a form?

My form includes a list of 6 options where users can only select one. After submitting the form, I want to redirect them to a specific page based on their selection. For example, I have the following 3 options: Facebook Youtube Twitter If a user selects ...

Vue's reactivity in Vue 3 is exhibiting strange behavior with boolean data

Currently, I am attempting to modify a boolean variable. Upon the initial page load, everything works as expected. However, upon reloading the page, the variable gets updated locally within the method but not in the global data section. As a result, an err ...

Troubleshooting issue with setting variables in Firefox's JavaScript

I have created a small JavaScript script that defines a value (referred to as stock), which I want to set as the maximum in a dropdown list. It will be set as the maximum value if it exceeds 6. Below is the code snippet: <script type="text/javascript" ...

Displaying overlay when sidebar menu is expanded

I am working on creating a smooth overlay transition for when the sidebar menu opens and closes. When the overlay is clicked, I want the menu to close. This is what I have so far: $(document).ready(function() { $('#menu-toggle').click(fun ...

In the realm of JavaScript, removing a DOM element can sometimes feel like an

For my project, I am using JavaScript, DOM, and AJAX to create pages. I am trying to figure out how to check if an element already exists and, if it does, remove it. This is what I have tried: var elementL = document.getElementById('divLogin'); ...

Error in API function call with AngularJS: Reference Issue

formApp.controller('load', function ($scope, ApiCall, $window, $http) { $window.onload = function () { alert("the page loaded and will now call the function"); ApiCall.GetApiCall("signOn", "GetSingleSignOn").success(function (data) { ...