What is the best way to fill a table with dates by using the date chosen by a user through the Angular UI datepicker?

I am looking to populate a table with 24 consecutive dates, starting from a selected date. For example, if I choose 7/1/2017, the table should display dates ranging from 7/2/2017 to 7/25/2017.

Previously, I achieved this using Jquery's datepicker as shown below:

<p id="dateStuff">
  Date: <br />
  <input type="text" id="datepicker">
</p>

Script for populating the table:

for (var i = 1; i <= 24; i++) {
  var result = new Date(currentDateString);
  var someFormattedDate = 0;
  result.setDate(result.getDate() + 1);
  var dd = result.getDate();
  var mm = result.getMonth() + 1;
  if (mm < 10) {
    someFormattedDate = '0'+ mm + '/' + dd + '/' + y;
  }
  else {
    someFormattedDate = mm + '/' + dd + '/' + y;
  }
  currentDateString = someFormattedDate;
  document.getElementById("date" + i).appendChild(document.createTextNode(currentDateString));
}

Now, I am trying to replicate this functionality using angular ui datepicker (http://angular-ui.github.io/bootstrap/#!#datepicker) and facing challenges in achieving the same result.

Snippet of my code using angular ui datepicker:

<div class="form-group">
  <label for="cpDate">Date</label>
  <div class="input-group">
    <input id="inputStartDate" type="text" ng-model="sc.model.date" class="form-control" ng-required="true"
      ng-focus="isDatePickerStartOpened=true"
      uib-datepicker-popup="MM-dd-yyyy"
      datepicker-options="datepickerOptions"
      is-open="isDatePickerStartOpened"
      close-text="Close"/>
    <span class="input-group-btn">
      <button type="button" class="btn btn-default form-control" ng-click="sc.showDatePickerStart($event)"><i class="glyphicon glyphicon-calendar"></i></button>
    </span>
  </div>
</div>

Script for angular ui datepicker:

var vm = this;
vm.model = {
  date: new Date(),
};
alert(vm.model.date.toString().substring(4, 15));

I am facing issues as the alert displays the date format as Jul 19 2017 instead of 7/19/2017. Additionally, I am unsure how to retrieve and manipulate the month, day, etc. similar to my previous implementation.

Answer №1

First, make sure to use vm.model.date instead of sc.model.date in your template.

Secondly, Angular provides a convenient date filter that allows for easy date formatting (remember to inject the $filter provider into the controller just like you would inject $scope):

var formattedDate = $filter('date')(vm.model.date, 'MM/dd/YYYY');
alert(formattedDate);

Thirdly, when working with Angular compared to JQuery or plain JS, focus on the model instead of the DOM. Avoid using selectors to target DOM elements and prioritize starting from the model. Concentrate on obtaining an array of desired date objects:

vm.dates = [vm.model.date];

for(var i=1; i<=24; i++) {
  vm.dates.push(addDays(vm.model.date, i));
}

function addDays(date, days) {
  var result = new Date(date);
  result.setDate(result.getDate() + days);
  return $filter('date')(result, 'MM/dd/yy');
}

Now that you have an array containing all the dates you need, utilize Angular's ng-repeat to present your table:

<table>
 <thead>
  <tr><td>Date</td></tr>
 </thead>
 <tbody>
   <tr ng-repeat="day in vm.dates">
    <td>{{day}}</td>
   </tr>
 </tbody>
</table>

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

Utilizing NgStyle and Property Binding in Angular to Manipulate Data (or a Different Approach)

Currently, I am diving into Angular programming and encountering an issue with property bindings. Let me share a snippet of my code: // TS FILE data[ {"id": "1", "name": "tester", "rev": "1"}, {"id": "2", "name": "tester", "rev": "1"}, {"id": "3", "name" ...

What is the process for implementing THREE.EdgesGeometry on a model imported using THREE.OBJLoader?

I have been attempting multiple times to add edges in a model loader using the OBJLoader, but I am unable to achieve it. Mloader = new THREE.MTLLoader(); Mloader.setPath( dir ); Mloader.load( mtl_dir, function ( materials ) { ...

The ng-class condition is in flux, however, the new style is not being

Attempting to modify the background of the pane in an Ionic application based on the condition of the ng-class as shown. Changing the condition in the code and refreshing the page manually works correctly, but updating the condition from user input does ...

Ensure that all form fields are completed and accurate before the Stripe payment modal is displayed

I've encountered an issue where the stripe payment modal appears before my form validation is complete. I am using the jQuery validation plugin for this purpose. I attempted to integrate the Stripe code within the submitHandler function, but it did no ...

The SelectedIndexChanged event fails to trigger following an onchange event

I am currently working on validating a dropdown list on the client side based on its selected index/value. My goal is to create a function that triggers an alert when the selected index is 0, or alternatively execute the SelectedIndexChandged method in the ...

Refresh the jQuery Carousel when the window is resized to switch the orientation from vertical to horizontal

I am in the process of creating a gallery for a responsive layout, utilizing jQuery Riding Carousels for the thumbnails. You can find more information about it here. One issue I am encountering is that when the window size shrinks to be smaller than 1024p ...

"Angular's ui-router allows for nested views with individual templates and controllers for each

I have the following list of files: index.html car.html truck.html mainCtrl.js carCtrl.js truckCtrl.js I aim to create the following routes: #/search (template: index.html, controller: mainCtrl.js) #/search/car (template: car.html, controller: carCtrl. ...

Extracting Data from Input Box Using Query

In my HTML setup, I have five <textarea> tags with IDs text1,text2,text3,text4, and one additional <textarea> tag with ID output. I want to query based on the values of text1,text2,text3,text4 (referred to as field1, field2, field3, field4). F ...

Tracking and managing user clicks on external links within a vue.js application

I am currently working on a web application that retrieves data from a CMS. Utilizing the Vue-Router in 'history' mode, I need to address content fetched from the API which may include links. My goal is to manage specific links using the router w ...

What is the best method for choosing the parent elements?

I am attempting to create a sidebar that saves the last clicked link in local storage and still displays the collapsed links after the page is reloaded. $(".clickedLink").parent().parent().css('background-color', 'green'); Ca ...

"Stay entertained with a captivating animated gif that appears when you refresh the

I just implemented this code snippet to enable animated gifs to work after refreshing a webpage. It's functioning properly in Chrome, Safari, and Internet Explorer except for Firefox. Can someone please offer assistance? jQuery: $(img).css("backgrou ...

Understanding JSON Arrays using jQuery

I've been attempting to display JSON objects in the console, but unfortunately, I'm facing some issues. The JSON data is obtained from a small API that I crafted using PHP. Here's a snippet of my JSON: { TotalResults: 2, Results: [ ...

.htaccess file is causing js and css files to not load

I followed an MVC tutorial by howcode on YouTube, but I encountered an issue where my CSS and JS files were not loading due to the htaccess configuration. .htaccess file: RewriteEngine On RewriteRule ^([^/]+)/? index.php?url=$1 [L,QSA] I attempted vario ...

Exploring Next.js with getStaticPaths for multi-language support

In my current Next.js project, I am working on implementing multiple locales for dynamic pages using i18n. Within my next.config.js file, the following configuration is set: module.exports = { i18n: { locales: ["en-US", "da-DK", "se-SE", "no-NO", "n ...

Retrieve the past week's data based on names using JavaScript

Is there a way to dynamically fetch the past seven day names, starting from today, in JavaScript? I am looking to format the result as follows: (Wednesday, Tuesday, Monday, Sunday, Saturday, Friday, Thursday, Wednesday). ...

Adding a class-matched element with a corresponding ID

Despite finding similar questions, I am still unable to achieve the desired outcome. Here is a list: <ul> <li class="class1"></li> <li class="class2"></li> <li class="class3"></li> <li class="class4"&g ...

The Autocomplete feature from the @react-google-maps/api component seems to be malfunctioning as it returns

I'm encountering some difficulties with the Autocomplete component in @react-google-maps/api. While Autocomplete is working and displaying options, clicking on an option fills the input box but I'm only getting 'undefined' from the Plac ...

Limitation on calling $http.get() multiple times is in place

Complete Rewriting Of Inquiry The situation has taken a new turn, prompting me to clarify the current scenario from scratch. My goal is to develop a straightforward message board using Node, Express, MongoDB, and Angular. On the server side, my get and ...

Error: The property 'title' is not defined and cannot be read

Javascript - Node.js - Express - MongoDB - Mongoose In my code, I am using a forEach() method that iterates through each user and manipulates an array by adding or removing items. Strangely, the method successfully adds the correct number of items for one ...

Is it possible to maintain a fixed footer while utilizing async/ajax functions?

Looking for a reliable solution to have a fixed footer that adjusts based on the page content? I've tested multiple samples, but they all fall short when it comes to incorporating AJAX elements. Is there a fixed footer out there that truly works seaml ...