Setting the current date as the default in an input box using ng-it: a step-by-step guide

How do I automatically set today's date as the default in the input box using ng-it?

  • Here is my Plunker

  • I am simply looking to set today's date as the default in the input field using ng-it.

  • Would appreciate it if you could check out my Plunker and provide some assistance, thank you.

My code snippet:

    <div ng-app="" ng-init="to='2018-01-24'">

<p>Default date in the input box:</p>
<p>Name: <input type="date" ng-model="to"></p>
<p>You wrote: {{ to }}</p>

</div>
  • In the Plunker, we are looking to have the value of the second input field set as today's date...

Answer №1

There seems to be some uncertainty regarding the ability to call native JS function/object in ng-init. It appears that a workaround is to create a proxy in the $rootScope (assuming there is only one ng-app):

Within your javascript:

 angular.module("foo", []).run(["$rootScope", function($rootScope) {

     $rootScope.date = new Date();
 }]);

In your HTML:

<div ng-app="foo" ng-init="firstname='John'; currentDate=date">

Following the previous javascript method, you should be able to directly utilize the date object (as demonstrated in your Plunker).

It is highly recommended to maintain only one app per page in AngularJS, as the auto-bootstrapping feature can only accommodate one ng-app (https://docs.angularjs.org/api/ng/directive/ngApp).

It is considered best practice to encapsulate all required scope within a controller.

Below is a partially updated Plunker (without the addition of a controller): http://plnkr.co/edit/BLVWN4jHIMwEuZzjA698?p=preview

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

Inserting data with special characters from an Ajax POST request into a database

I am facing an issue with my form that contains text inputs. When I use an ajax event to send the values via POST to my database PHP script, special characters like ' " \ cause a problem. If the string contains only numbers/letters and no special ...

What is the proper method for utilizing the .done or .complete functions in conjunction with .toggle in jQuery?

I am struggling to understand the proper usage of .complete or .done after .toggle in jQuery. My goal is to have the button's text change after the toggle animation finishes, but I'm not sure if I'm chaining them correctly. The jQuery docume ...

JavaScript conditional statement malfunctioning

I am currently facing an issue with my JavaScript script. I am using jQuery to send data via AJAX to a PHP file and expecting a text dataType in return so that I can test it with JavaScript. My objective is to redirect the user to another webpage if the t ...

What is the best approach for managing a drop-down menu in Protractor test automation?

I am a beginner with this tool and have experience handling drop down menus in Selenium WebDriver. Can anyone provide guidance on how to handle drop down menus using the Protractor tool? Any tips, tech forums recommendations would be greatly appreciated. ...

Challenges with Organizing Data and Maintaining Database Integrity

I have been working on making this sortable code function properly. Initially, I had it working fine with <li> elements as shown in the UI examples. However, now I am trying to implement it with <div> elements. While it shouldn't be much o ...

Angular2 (RC5) global variables across the application

I am seeking a solution to create a global variable that can be accessed across different Angular2 components and modules. I initially considered utilizing dependency injection in my `app.module` by setting a class with a property, but with the recent angu ...

Step-by-step guide on uploading a template in unlayer-react-email-editor

<EmailEditor ref={emailEditorRef} onReady={onTemplateReady} /> const onTemplateReady = () => { try { const templateJson = htmlToJSON(savedData?.email?.content); console.log({ templateJson }); emailEditorRef?.current?.editor?. ...

using vuejs, learn how to retrieve properties within the .then function

This is the code I am working on: methods: { async pay() { this.$notify(`working`); if (!this.$v.$invalid) { try { var data = { to: this.to, subject: this.subject, }; let resp ...

FullCalendar Angular 10 not displaying correct initial view

I am currently using Angular 10 along with FullCalendar version 5.3.1., and I am facing an issue where I cannot set the initial view of FullCalendar to day view. It seems to be stuck on the dayGridMonth view by default. Below is the HTML snippet: <full ...

Is there a way to customize the color of the bar displaying my poll results?

My poll features two results bars that are currently both blue. I attempted to change the color of these bars but was unsuccessful. I've searched for solutions on stack overflow, specifically How can I change the color of a progress bar using javascr ...

Why is my event.target.value not updating correctly in React useState?

My problem is that when I use useState, I am receiving incorrect numbers For example, if I print e.target.value it might display 1, but my selectedIndex shows 2. Similarly, when I have a selectedIndex of 0, it retrieves something different like 1. Any tho ...

Just starting out with d3, any easy methods to learn?

As a developer with a few years of experience under my belt, I recently discovered d3 and was really impressed by its capabilities. However, it seems like d3 doesn't have the same level of popularity as jquery, making it harder to find comprehensive d ...

Renaming properties in an AngularJS model

After receiving the data in a structured format, my task is to present it on a graph using radio buttons. Each radio button should display the corresponding category name, but I actually need each button to show a custom label instead of the original categ ...

Dual Image Flip Card Effect for Eye-Catching Rotations

In the process of enhancing a website, I am interested in incorporating a feature that involves multiple cards with both front and back sides (each containing separate images). Initially, the plan is to display only the front side of the card. Upon clickin ...

What is the best way to seamlessly transition layers from one location to another as the mouse exits and re-enters the window?

I have been working on refining a parallax effect to achieve a seamless transition between two positions based on where the mouse exits and enters the window. In the JSFiddle example provided, there is a slight 'pop' that I am looking to replace ...

Comparing two Objects in JavaScript results in automatic updates for the second Object when changes are made to the first

Can someone please assist me with a hash map issue I'm encountering in my for loop? When resetting the second object, it unintentionally alters the Map values of the previous Key in the Hash Map. Any guidance on how to prevent this behavior would be g ...

Utilizing Puppeteer to Navigate and Interact with Elements Sharing Identical Class Names

I am new to Puppeteer and NodeJs, and I am attempting to scrape a specific website with multiple posts that contain a List element. Clicking on the List element loads the comment section. My question is: I want to click on all the list elements (since th ...

What is the best way to create a unit test for a controller that utilizes $state?

Currently working on creating a unit test for my controller: app.controller('StartGameCtrl', function ($scope, $timeout,$state) { $scope.startGame = function () { $scope.snap = false; $scope.dealCards(); debugger; ...

Storing information in local storage based on the currently logged-in user

Is there a way to store the information of the currently logged in user using AngularJS? For example, if user1 is logged in, can I display only that user's details on the page? How can I assign unique keys for each logged in user? ...

Mongoose and MongoDB in Node.js fail to deliver results for Geospatial Box query

I am struggling to execute a Geo Box query using Mongoose and not getting any results. Here is a simplified test case I have put together: var mongoose = require('mongoose'); // Schema definition var locationSchema = mongoose.Schema({ useri ...