Converting Datepicker selection to a string format in AngularJS

Can anyone help me figure out how to convert a datepicker value into a string that can be passed as a parameter to a get method without causing an error?

<div ng-app="getserviceApp" ng-controller="getserviceCtrl">
        <button ng-click="FunctionLoadData()">Load Data</button>

        <input type="date" ng-model="from_date" />
        <input type="date" ng-model="to_date" />

<script type="text/javascript">

        var app = angular.module('getserviceApp', [])

        app.controller('getserviceCtrl', function ($scope, $http) {

            var FromDate = new Date($scope.from_date.selectedDate);
            var ToDate = new Date($scope.from_date.selectedDate);

Answer №1

Ensure that your ng-models match the name of your $scope variables in your controller.

Within your controller, it should look something like this:

   app.controller('getserviceCtrl', function ($scope, $http) {
     $scope.from_date = new Date();
     $scope.to_date = new Date();

     $scope.loadData = function(){
       console.log($scope.from_date.toISOString().split('T')[0])
       console.log($scope.to_date.toISOString().split('T')[0])
       //prints the dates in yyyy-MM-dd format
     }
   }

And in your HTML file:

<div ng-app="getserviceApp" ng-controller="getserviceCtrl">
    <button ng-click="loadData()">Load Data</button>

    <input type="date" ng-model="from_date" />
      value = {{from_date | date: "yyyy-MM-dd"}}//Display the date
    <input type="date" ng-model="to_date" />
      value = {{from_date | date: "yyyy-MM-dd"}}
</div>

Answer №2

It seems like the mistake lies in using from_date.selectedDate. Instead, try only using the model from_date

You can test it out on this functional stackblitz.

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

Tips for Optimizing Typescript Queries to SQL Server

In my C# application, I have the following function: foreach (var p in proglist) { programData.GetData1= new List<GetData1_ViewModel>(GetData1(programid, reportingdate)); programData.GetData2= new List<GetData2_ViewModel>(GetData2(programid ...

"Placement of script tag within the body and the function of the appendChild method

What do you think will happen in the example provided below? The majority of current browsers (such as Firefox 5, Chrome 14, Opera 11.50) will place the iframe above the text. Is this behavior standardized or just a common practice that could potentially ...

Is there a more efficient method for writing my jQuery code that follows a step-by-step approach?

I have developed a step-by-step setup process that guides users through various sections. Instead of using separate pages for each step (like step1.php, step2.php, etc.), I have all the code contained in one page named setup.php. This is achieved by utiliz ...

Execute the command "Assign role Discord.js" in Discord

Trying to create an 'add role' command using Discord.js, but the bot is not adding the role as expected. if (message.content === config.prefix + 'addrole') { const targetUser = message.mentions.users.first() if (!targetUser) { ...

Sorting an array of strings that contain years in JavaScript

I am attempting to organize an array of seasons based on season and year, all while eliminating any duplicate seasons. Merely sorting the array did not produce the desired outcome, so I believe utilizing a regex might solve the issue. const myStringArra ...

Efficient PHP caching solution for optimizing JavaScript and CSS performance

I'm facing a unique challenge that I can't seem to solve through typical Google searches. I'm in the process of consolidating all my javascript and css into separate php files using require_once() to pull in the content. The structure of my ...

The placement of the FirebaseAuth.onAuthStateChanged call in an Angular application is a common concern for developers

Where is the best place to add a global listener initialization call in an Angular app? Take a look at this code snippet: export class AuthService { constructor( private store: Store<fromAuth.State>, private afAuth: AngularFireAuth ) { ...

How to toggle the selection of all checkboxes in an AngularJS ng-repeat object array

Check out this Fiddle Example In my table, each row contains a checkbox and there is also a checkbox to check all rows and send the ID of the selected/all rows as JSON object. I have an array of objects from the server-side response (with pagination enab ...

The carousel feature in AngularJS's bootstrap is currently experiencing technical difficulties

SOLVED: Look at this Codepen link for the correct code: Codepen Why is my angular bootstrap carousel displaying images stacked on top of each other without sliding? This is how I have set it up: HOME.HTML: <div id="slides_control"> <div> ...

Utilizing jQuery show() and hide() methods for form validation

I created a form to collect user details and attempted to validate it using the jQuery hide and show method. However, I seem to be making a mistake as the required functionality is not working correctly. What am I missing? I have searched for solutions on ...

Is there a framework available to animate Pseudo CSS elements?

Recently, I was working on developing a bar chart that utilized pseudo CSS elements (::before, ::after). While I successfully created bars that look visually appealing, I encountered a challenge when attempting to animate the height changes. Whenever I us ...

How can I most effectively establish defaultValues for react-hook-form in this scenario?

I am working on a static Next.js website with only frontend functionality. In the pages/feedback/[id]/edit.tsx page, I need to dynamically retrieve an id and set default values in a nested FeedbackForm component. export const FeedbackForm = ({ editing }: { ...

Add a container element resembling a div inside a table without implementing the table layout

I am working with a table that is rendered by DataTable, and I have the requirement to dynamically append new elements inside the table like this: The dark grey area represents the new DOM elements that need to be inserted dynamically. The first row cont ...

Is it possible to use JavaScript to load, edit, and store text files?

Hey there, I have a text file that needs some find and replace operations done on it within the browser. My coding skills are still in the beginner stage, so creating web apps from scratch feels overwhelming right now. All I want to do is upload the file, ...

I am looking to incorporate two YouTube videos into an HTML webpage, each in a different language. I would like to provide the option for users to select the language, even though the content

I am looking to target a global audience with my website, so the content is in English. However, I want to offer users the option to watch videos in their preferred language. I have recorded content in 4 different languages that might enhance engagement on ...

How to eliminate space preceding a div using jQuery?

I am trying to modify the following code snippet: <div id="one">1</div> <div id="two">2</div> <div id="three">3</div> Is there a method for me to eliminate the space before div "three" in order to achieve this result: ...

What is the process for importing specific modules from jQuery?

When working with webpack or browserify, what is the specific procedure required to import only the essential modules from jQuery as mentioned here? import {core, dimensions} from 'jquery' Unfortunately, this approach does not seem to be effect ...

Convert a number to binary in JavaScript, but display the result as infinity

data = parseInt(num); bin =0; pow=1; var rem=0 ; while(data != 0){ rem = data % 2; data = data / 2; bin = rem * pow + bin; pow = pow *10; } document.write(bin); I encountered an issue with my JavaScript code. Even though the example should output 11011 ...

Retrieve the most recent ajax request and cancel any other ones

I've been exploring this issue and it seems fairly straightforward, but I'm having trouble finding a solution. I have several requests that call different URLs. However, for each URL, I only want to receive the last result from the same URL being ...

Combining attributes of array elements using ReactJS

Imagine this scenario with a JSON structure received from a server AJAX request: { "Items": [ { "ID": 1, "Name": "John Smith" }, { "ID": 2, "Name": "Jane Doe" } ]} Let's say we have a Fetch function that takes the JSON data ...