Modifying the value of a date picker input using an Angular button

I have an input field with an attached Angular UI datepicker, and I have also added two buttons below to change the date "day by day".

Here is the input section on my page:

<p class="input-group">
    <span class="input-group-addon hidden-xs">From</span>
    <input type="text" class="form-control text-center" datepicker-popup="{{format}}" ng-model="parent.dtFrom"   ng-change="refresh(0)" show-button-bar="false" is-open="opened1" max-date="maxDate" datepicker-options="dateOptions" ng-required="true" close-text="Close" readonly />
    <span class="input-group-btn">
        <button type="button" class="btn btn-default" ng-click="open($event, 'opened1')"><i class="glyphicon glyphicon-calendar"></i></button>
    </span>
</p>

And here are the buttons for changing it:

 <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 btn-group" role="group" >
   <div class="text-center" >
     <button type="button" class="btn btn-default btn-outline glyphicon glyphicon-chevron-left text-center previousdate" ng-click="addDayFrom(-1)"></button>
     <button type="button" class="btn btn-default btn-outline glyphicon glyphicon-home text-center todaydate"  ng-click="DateFromToday()"></button>
     <button type="button" class="btn btn-default btn-outline glyphicon glyphicon-chevron-right text-center nextdate" ng-click="addDayFrom(1)" ng-show="parent.dtFrom < todate" ></button>
   </div>
 </div>

This is how I initialize dtFrom at the beginning of my controller:

$scope.parent={
    dtFrom : new Date(),
    dtTo : new Date()
};

And this is the function to change dtFrom:

$scope.addDayFrom=function(day){
    $scope.parent.dtFrom.setDate($scope.parent.dtFrom.getDate() +  parseInt(day));
    console.log($scope.parent.dtFrom);
};

It changes the value in $scope.parent.dtFrom but the model isn't updated in the input.

For example, if today's date is 12/05/2015.

If I click the previous button once, $scope.parent.dtFrom will be 11/05/2015.

This reflects correctly everywhere except in the input field.

I believe it may be a scope issue, but I can't pinpoint where it's happening. Do you have any suggestions on how to fix this?

Edit: View image here:

Answer №1

Revise your code snippet to:

$scope.addDayFrom=function(day){
    $scope.parent.dtFrom = ($scope.parent.dtFrom.getDate() +  parseInt(day));
    console.log($scope.parent.dtFrom);
};

Take a look at the Angular UI datepicker documentation for guidance on accessing properties without using parent. It seems like you were unintentionally accessing the parent attribute rather than the parent scope in this scenario:

$scope.parent={
    dtFrom : new Date(),
    dtTo : new Date()
};

The Angular UI datepicker utilizes reference-based tracking, as evidenced in their source code. This is an efficient approach for monitoring changes. To gain a deeper understanding of this concept, refer to the documentation on Scope $watch Depths in Angular core:

Scope $watch Depths

There are three strategies for dirty checking: by reference, by collection contents, and by value. These strategies vary in terms of the detected changes and performance characteristics.

  • Watching by reference detects a change when the entire value returned by the watch expression is updated to a new value. Changes within arrays or objects are not monitored. This method is the most efficient.
  • Watching collection contents tracks changes occurring inside arrays or objects, such as additions, removals, or reordering. The detection is shallow and does not extend into nested collections. While more costly than watching by reference, this strategy aims to minimize copying operations.
  • Watching by value identifies any modification within a nested data structure. Although powerful, it is the most resource-intensive option, requiring complete traversals and memory storage of the data.

The issue with

$scope.parent.dtFrom.setDate(newDate)
not triggering updates was due to how the model wasn't being recognized. Simply modify the code to $scope.parent.dtFrom = newDate for proper functionality (similar to how it operated with your previous global variable method).

Answer №2

Although it may be considered a bit of a hack, this method actually works, so I thought I'd share it with you.

When starting my application, I create a local date variable that I update when my button is clicked. Once completed, I execute the following code:

$scope.parent.dtFrom = new Date(localDateVariable);

It may not be the most elegant solution, but it is a solution nonetheless.

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

Issue with Material-ui IconButton's edge properties not functioning as expected

Is there a way to position the delete icon on the right side of the screen? It seems like using edge= "end" is not working as expected. If you'd like to take a look, here is the sandbox link: https://codesandbox.io/s/admiring-silence-vwfoe? ...

AngularJS does not run the code inside the ref once directive

Code within the block of this.verifyUserToken does not execute. It appears that the issue may stem from asynchronous calls, as the data returned is not yet available. I am unsure of how to proceed in handling this. this.verifyUserToken = function(){ ...

Exploring the possibilities of implementing Undo and Redo features in freehand drawing with Reactjs on

After attempting to create a Freehand drawing using HTML5 canvas with React, my next step is to incorporate an undo and redo functionality when the corresponding buttons are clicked. I would greatly appreciate any assistance provided. function App(props) ...

React.Children does not reveal the presence of any offspring

I am looking to implement react-native-maps-clustering in my project. However, this library only accepts markers that are direct children of the maps component. An example of how it should be structured: <MapView> <Marker/> <Marker/> ...

Issue with integrating Google Spreadsheet as the data source for a Next.JS website: updates are not reflecting on the website pages

The website for this restaurant was created by me, using Google Spreadsheet to populate the menu pages. I chose this method for its simplicity and familiarity to the client. I'm utilizing the google-spreadsheet package to extract necessary informatio ...

Ways to hide notifications by setting a timer while keeping the delete option visible

Presently, this is the code I am working with using Javascript and Vue.js. I have an array called Messages.length that contains messages. When the x button is clicked, it triggers the "clearMessages(item)" function on the server side. However, I also aim ...

Issue with Angular: Unable to properly sort data while modifying queryParams

Within the component.ts file: export class TabsComponent implements OnInit { constructor( private store$: Store<UsersState>, private router: ActivatedRoute ) {} ngOnInit(): void { this.onFilterByIncome(); this.router.queryParam ...

Can you provide guidance on utilizing the Login Event within the Electron Framework?

I need some assistance in understanding the functionality of the Event: 'login' feature within the Electron Framework. Is this similar to the Password Autofill/Remember Password feature typically found in web browsers? I'm interested in util ...

Refreshing the page causes ngRoute to malfunction or results in an unknown route error

I am encountering an issue with my code. Whenever I refresh the page on localhost:portnumber/home or /todos or /contacts, it crashes -> showing an error "Cannot GET /home" or /todos or /contacts. The same problem occurs if I just enter localhost:port ...

Error 404: Angular version 18 - Request not found

After upgrading my Angular application to version 18 (18.0.1), I've encountered issues with http requests on localhost. The majority of my requests are returning a 404 error. I am operating behind a corporate proxy and have a configuration file in pla ...

Import JavaScript from a PDF using Java's iTextPDF library

I have successfully created a PDF from Java using the iText PDF library. However, I am facing an issue where I cannot add JavaScript code either from HTML when onload is called or from Java code. I am not receiving any exceptions. What am I doing wrong? Is ...

Clicking on an element triggers the addition of a class, and the newly

Once the page has finished loading, I am able to utilize jQuery to add a specific class in the following way. $(document).ready(function() { $("#parent").click(function(){ $(".child").addClass("active"); }); }) ...

The .map() operator requires a declaration or statement to be specified - TS1128 error

I've tried various solutions from different sources but none seem to be resolving the issue I'm facing. The problem is: when trying to run my app, I encounter the following error: 10% building modules 0/1 modules 1 active …\src\a ...

Invoke multiple stored functions using JavaScript, beginning with this one

One way to store and call a function later is by assigning it to a variable, like so: var storedFunction = functionName; //Later On storedFunction(); //Equivalent to functionName() If you want to store a function and also execute 'this' when ca ...

Is there a way to retrieve the index and specific object that was modified using $watch in Angular?

I am receiving an array of objects from an API that is being updated every 2 seconds. I have a $watch function that is monitoring any changes in this array. I want to be able to identify which elements have changed along with their index, so that I can dyn ...

Ending or stopping based on data retrieved from an ajax call

Currently, I have a php script that includes an image which, upon clicking, redirects the user to a different page. Additionally, there is an ajax/jQuery function in place to check if the user is logged in or not. When the user clicks on the link, the aja ...

Developing instance members and methods in JavaScript

After encountering a challenge with creating "private" instance variables in JavaScript, I stumbled upon this discussion. Prior to posing my question, I wanted to provide a thorough overview of the problem. My goal is to showcase a complete example of corr ...

Tips for sending a parameter within a JavaScript confirm method?

I currently have the following code snippet in my file: <?php foreach($clients as $client): ?> <tr class="tableContent"> <td onclick="location.href='<?php echo site_url('clients/edit/'.$client->id ) ?>&ap ...

Having difficulties linking the front end and the back end despite diligently following the tutorial

Currently, I am experimenting with creating a real-time chat application by following a tutorial on YouTube from JavaScriptMastery. The tutorial link is here, and the GitHub repository is available at this link. Despite closely mimicking the code displayed ...

What is the best way to incorporate animation into Bootstrap dropdowns?

Is there a way to incorporate animation into the dropdown feature? I'm assuming it can be achieved by adjusting popperConfig, but how exactly? Currently, the dropdown-menu has an automatically generated inline style, for example: position: absolute; ...