Angular-Daterangepicker: Dynamically Updating Start Date Selection

I am currently utilizing the date-range picker from https://github.com/fragaria/angular-daterangepicker and to showcase a calendar for selecting travel dates in my application. Depending on the type of flight chosen, I need either a date range for roundtrip flights or a single date for one-way flights. The issue I am facing is that the date object only gets updated upon selecting the end date, not the start date.

This is the controller function code snippet:

//oneTripDate Calendar controller
 app.controller('OnewayPickerCtrl',['$scope','$rootScope', 'searchFactory',
function($scope, $rootScope, searchFactory) {
    $rootScope.flyDates = { departureDate : '' };
    $scope.onewaydate = {
        startDate: searchFactory.search.searchparams.journeys[0].departuredate, 
        endDate: searchFactory.search.searchparams.journeys[0].returndate
    };
    $scope.opts = {
        autoApply: true,
        minDate: moment(),
        startDate: moment(),
        alwaysShowCalendars: true,
        parentEl: '.cal-block .form-group',
        autoUpdateInput: true,
        singleDatePicker: true
    };

    //Watch for date changes
    $scope.$watch('onewaydate', function(newDate) {
        console.log('One Way model Changed');
        searchFactory.search.searchparams.journeys[0].departuredate = moment(newDate.startDate).format("YYYY-MM-DD");
    }, false);
}
]);

Below is where I have added the input field to enable the conversion to a datepicker:

<div data-ng-controller="OnewayPickerCtrl">
      <input date-range-picker id="onewaydate" name="onewaydate" class="form-control date-picker" options="opts" type="text" value="" ng-model="onewaydate" required/>
</div>

Although I am monitoring changes in the model to capture any modifications and then applying the value to my factory, it seems to work flawlessly for date ranges because the change is detected upon the second selection. However, it does not function as expected when only a single selection is made. In essence, the watch event on onewaydate triggers only after the second selection.

If you have encountered this scenario before, I would greatly appreciate any insights or advice.

Answer №1

An issue arises with the Single Date picker when it is forced to be inline, as it does not properly "close." Consequently, the model fails to update, resulting in missed selections beyond the initial one. This leads to the $watch function failing to trigger.

My solution to this problem is outlined below and has proven effective:

    $scope.optsOneway = {
        minDate: moment(),
        maxDate: moment(new Date().setFullYear(new Date().getFullYear() + 1)),
        autoUpdateInput: true,
        autoapply: true,
        singleDatePicker: true,
        parentEl: '.cal-block .form-group .oneway',
        eventHandlers: {
            'apply.daterangepicker': function(ev, picker) { 
                angular.element('#onewaydate').triggerHandler('click'); //one way calendar
            }
        }
    };


   //Watch for date changes
    $scope.$watch('onewayDate', function(newDate) {
        searchFactory.search.searchparams.journeys[0].departuredate = moment(newDate).format("YYYY-MM-DD");
        angular.element('#onewaydate').triggerHandler('click'); //one way calendar
    }, false);

While my approach may seem somewhat unconventional, I continuously re-trigger the datepicker whenever a value is assigned. It appears that this specific Datepicker was not intended for the usage we are implementing.

I hope this solution proves useful to others facing a similar challenge.

Best regards,

Answer №2

Having faced a similar issue in the past, I understand your frustration. If you could provide a fiddle showcasing the problem, it would make troubleshooting much simpler.

Upon examining the library, I stumbled upon a potentially helpful solution for you:

https://github.com/fragaria/angular-daterangepicker/blob/master/js/angular-daterangepicker.js

On line 155, I found this interesting snippet of code:

$scope.$watch('model.startDate', function(n) {
         //some event
          return _setStartDate(n);
        });

By triggering an event from this section, you may be able to achieve the desired outcome.

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

The module './installers/setupEvents' could not be located within Electron-Winstaller

After encountering an error while attempting to package my Angular app on Windows 10, I'm looking for help in resolving the issue: https://i.stack.imgur.com/yByZf.jpg The command I am using is: "package-win": "electron-packager . qlocktwo-app --ove ...

During bundling, utilize an npm script to copy the package.json file to the dist directory

Currently, I am facing a challenge while trying to enhance my npm bundle script. Although the initial part is functioning smoothly, I am encountering difficulties in including three additional files along with the bundle. At present, my script looks like ...

No reply received on the web browser

I have written a code that is intended to read a JSON file and display it in the browser. The code is functioning correctly as it prints the data to the console, but for some reason, the data is not displaying on the browser. app.post("/uploadfile&q ...

Angular filter within a nested ng-repeat loop

I've encountered an issue with nested filtering in Angular, where two filters are dependent on each other. What I'm trying to achieve is the following: <div ng-repeat="g in groups | filter:groupFilter"> ... <tr ng-repeat="c in g.co ...

Relocate the bxslider carousel to the specific div clicked on

Is it possible to move the slider to the selected div when using bxslider? I have a carousel below. Currently, when you click on the controls (left/right arrows), it only moves one slide/div at a time, keeping the active div always on the left side. Howev ...

Unusual JavaScript Bug: Uncaught TypeError - Unable to access property 'url' of null

I encountered a peculiar JavaScript error. The following message appears in the console: Uncaught TypeError: Cannot read property 'url' of null (Line 83) The code on Line 83 looks like this: var image = '<img class="news_image_options ...

Scheduling classes based on their index or data attributes

Here is a code snippet demonstrating the use of a variable instead of a hardcoded value: var i = 1; if ($(this).attr('data-target="1"')){} To pass the variable i instead of 1, you can modify the code like this: if ($(this).attr('data-targ ...

What is the procedure for updating or adding data to a JSON file with angularJS?

After successfully creating a local JSON file and retrieving data from it using app.controller('appCtrl', function($scope, $http){ $http.get('employees.json').success(function(data){ $scope.employees=angular.fromJson(data.employee ...

Prevent incomplete date input in Html5 date input field

Is it possible to make an input type="date" field, which is not required, treat partially completed dates entered by the user (e.g. month and day without year) as invalid rather than silently accepting them? I would like to alert the user in this scenari ...

Pattern-Based jQuery Selectors

I am looking for a way to use jQuery to select all paragraphs < p > within a < div > that contain time stamps with the following formatting patterns: <p>[22:48]</p> or <p>[22:48 - Subject Line]</p> Can someone provi ...

Chart.js is failing to display the chart when integrated with RequireJS

I have been attempting to display a chart using Chartjs and Requirejs, but unfortunately, it is not rendering properly and no error messages are being displayed. I am aware that I may be overlooking something simple due to fatigue, but I am unable to pinpo ...

There seems to be an issue with Next.js retrieving an image from an external localhost

I'm facing a challenge in my current Next.js 14 project where I am encountering an issue when attempting to display an image from localhost:8081 using the Image component from 'next/image'. The backend is written in Java and it sends the ima ...

What tips should be followed when setting up the stencil repository?

Is there a preferred method for defining fields when setting up a Stencil store? The documentation provided online primarily showcases examples with numbers, but what about situations involving objects, strings, or booleans? Should we use the 'as&apo ...

How can you assign a default value in a React select dropdown and dynamically add the remaining values?

I'm currently developing a React application that includes a form with a select dropdown feature. My goal is to have the 'uom' field value from the selected product record automatically set as the default option in the dropdown when the user ...

Troubleshooting Vue.js Error: Uncaught ReferenceError - jQuery Undefined

I'm a beginner with Vue.js and I'm attempting to develop a custom component that utilizes the jQuery formBuilder plugin from formBuilder. However, when I try to include this component file within another component, an error occurs: Uncaught Re ...

How come despite installing node 10.1.0, the system is showing the installed version as 5.6.0?

After I downloaded the NPM Windows installer from this link: https://nodejs.org/it/, I made sure to download and install the 10.1.0 version. However, when I checked my console using the command node -v, I was surprised by the following output: C:\U ...

"Is there a way to reverse the action of $( "button" ).remove()

Currently, I have implemented JQuery's $( ".button" ).remove(); function to get rid of all the buttons on my webpage immediately after a user clicks the print PDF button that changes the HTML page into a PDF. Nevertheless, once this process is done ...

Encountering an issue while fetching data from the server - Unable to access properties of undefined (specifically 'toString')

I have encountered an issue where I am trying to set the default value of a select element to the data received from the server. Despite knowing that user.roleId is not undefined, I am getting an error specifically with the select element. Other input elem ...

"Printed within the custom directive, the ng model value shows up as undefined

I am currently in the process of creating a custom directive that involves a simple template consisting of an input type textarea. I am assigning the ng-model to ngmodel and creating a link function where I am trying to capture the value of ngmodel. Howeve ...

Analyzing npm directive

I have a script that handles data replacement in the database and I need to execute it using an npm command package.json "scripts": { "database": "node devData/database.js --delete & node devData/database.js --import" ...