ng-model not reflecting the updated value

I am currently facing an issue with my date inputs. I want the second date input to default to the value of the first date input, allowing the user to change only the second date if needed.

Although the second date input updates correctly when I modify the first date, the ng-model does not reflect this change in the form_data.to_date attribute. As a result, the form remains invalid even though both required fields are filled out.

To illustrate the problem, consider the following example:

angular.module('myApp', [])
  .controller('myController', function($scope) {
    $scope.form_data = {
      from_date: '',
      to_date: ''
    };
    
    $scope.f = function() {
      setTimeout(function() { // delay to show that to_date is not updating
        console.log($scope.form_data);
      }, 1000);
    }
  });

angular.element(document).ready(() => {angular.bootstrap(document, ['myApp']);});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-controller="myController">
  
  <form name="myForm">
    <input type="date" 
           ng-model="form_data.from_date"
           name="from_date"
           ng-change="f()"
           required />
           
    <input type="date" 
           ng-model="form_data.to_date" 
           name="to_date"
           ng-value="form_data.to_date || form_data.from_date | date: 'yyyy-MM-dd'"
           required />
           
    <p>Form invalid: {{myForm.$invalid}}</p> <!-- Should be false when first date is changed -->
  </form>
</div>

How can I ensure that the ng-model on the second date input reflects changes when the value in the first input is updated?

Answer №1

One reason for this behavior is the utilization of

ng-value="form_data.to_date || form_data.from_date | date: 'yyyy-MM-dd'"
. Essentially, if the value of form_data.to_date exists, it will be assigned; otherwise, form_data.from_date takes its place. However, please note that this action does not update the value of the ng-model.

To rectify this issue, consider adjusting your code as shown below:

    angular.module('myApp', [])
     .controller('myController', function ($scope) {
        $scope.form_data = {
          from_date: '',
          to_date: ''
        };
        $scope.f = function () {
          setTimeout(function () { // adding a delay to demonstrate the lack of updates in to_date
            if ($scope.form_data.to_date == "") {
              $scope.form_data.to_date = $scope.form_data.from_date;
            }
            console.log($scope.form_data);
            $scope.$apply();
          })
        }
    });
    angular.element(document).ready(() => { angular.bootstrap(document, ['myApp']); });   
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-controller="myController">
    <form name="myForm">
        <input type="date" ng-model="form_data.from_date" name="from_date" ng-change="f()" required />
        <input type="date" ng-model="form_data.to_date" name="to_date"
            ng-value="form_data.from_date | date: 'yyyy-MM-dd'" required />
        <p>Form invalid: {{myForm.$invalid}}</p> <!-- This should return false after changing the first date -->
    </form>
</div>

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

What is the best way to organize this array containing hash elements?

Similar Question: How can I sort an array of javascript objects? The data output I'm dealing with is structured like this: [ { value: 1, count: 1 }, { value: 2, count: 2 } ] My goal is to loop through the hashes in the array and return the valu ...

Utilize esbuild to monitor for any modifications, recompile the code, and automatically restart the express server

In my endeavor to develop a basic SSR-powered project using express + react, I find the need to monitor frontend and backend scripts concurrently in the development process. The primary objective is to utilize express routes in directing to react page com ...

Guide on how to incorporate a Wistia Channel video gallery into a Gridsome webpage/template

I'm currently working on a Gridsome website and I'd like to incorporate a Wistia Channel video gallery into one of the pages. Specifically, I want to place it within the "frame" div class on top of the existing image. However, I'm unsure abo ...

Error message: "Upon initial loading, Angular and Firebase are unable to map undefined"

After the initial load, it functions properly. However, I am seeking a way to implement a promise to prevent data mapping before it has fully loaded. Upon the first loading of the site, the error below is displayed. This issue may arise from attempting to ...

Encountering a console error during the migration of a Vue App with VueRouter

I am currently in the process of integrating a standalone Vue application into a larger Java Spring web project. The Vue app relies on Vue router as a dependency. However, when attempting to load the main page, I encountered an error in the browser console ...

Solving Addition and Subtraction Errors in Javascript/Jquery

Upon running the script below, it aims to calculate the height of the browser, as well as the heights of both the header and footer, subtracting them from the initial browser height: var a = $(window).height(); alert (a); var b = $('#header').cs ...

How do I go about showing every character on a separate line using a for loop?

var input = prompt("What is Lance attempting to convey?"); //user enters any text for (var i = 0; i <= input.length; i++) { var output = input.charAt(i); if (output == "e" || output == "o" || output == "a" || output == "u") { outp ...

Is there a way to set a value for an attribute in a form post submit button click?

I need to update the value of a form when the user selects "null" <form name="myForm" action="formProcess.php" method='post' onSubmit="return validateForm()"> <label for="venue">Venue:</label> <select name="venue"> ...

Incorporating a JavaScript advertisement zone within a PHP function

Currently in the PHP template, I am trying to embed a JavaScript ad zone inside a function in order to have control over each page's ad placement. Here is what I have: <?php if(is_page('welcome-president')) { oiopub_b ...

find the middle element in the Vue array

Currently in the process of developing a custom Vue carousel component, I have utilized some code snippets from this resource: link My goal right now is to enhance the slider with additional navigation bullets. However, due to the justify-content:center p ...

Default cross-origin behavior of the Fetch API

According to the Fetch Specifications, the default Fetch mode is 'no-cors'. The specifications state that a request's mode can be "same-origin", "cors", "no-cors", "navigate", or "websocket". Unless otherwise specified, it defaults to "no ...

Opera's compatibility with jQuery's Append method allows developers to

I recently wrote a jQuery script that interacts with a JSON feed and dynamically creates HTML code which is then added to a designated div on my WordPress site. Surprisingly, the functionality works flawlessly in all browsers except for Opera - where not ...

JavaScript API Response - conditional statement for handling a 'null' response

Does anyone have any suggestions for the following scenario: I have a response in .json format containing personal data of a person, who may or may not be assigned to a project. Here is an example response where the person is not assigned to a project: & ...

Refreshing JSP Pages with Updated ActionBean Variables in Stripes Framework

Having recently started working with Stripes, I am trying to customize the number of records displayed on a paginated table based on the dropdown selection ("show ## records per page"). However, I am struggling to set the value of the "recordsPerPage" vari ...

How to set a canvas as the background of a div element

Check out my code snippet below: <!DOCTYPE html> <html> <body> <div id='rect' style='width:200px;height:200px;border:1px solid red'> </div> <canvas id="myCanvas" style="borde ...

Troubleshooting Navigation Bar Toggle Button Issue in Bootstrap 5

Currently, I am in the process of working on a web project that requires the implementation of a responsive sidebar. This sidebar should be toggleable using a button located in the navigation bar. My choice for the layout is Bootstrap, and I have come acr ...

Issues with Laravel and AngularJs routing: When a simple route does not trigger the controller

Looking for some assistance with integrating AngularJs into my Laravel application within a blade partial. I have ensured that all necessary files are included, added the ng-app, and verified that there are no JavaScript errors occurring. However, I am enc ...

Is it possible to reduce a field value in firestore after successfully submitting a form?

I have a variety of items retrieved from firestore: availability : true stocks: 100 item: item1 https://i.stack.imgur.com/hrfDu.png I am interested in reducing the stocks after submitting a form. I used the where() method to check if the selected item m ...

display picture upon modification

Is there a way for me to display the image I choose in AngularJS, similar to uploading an image on StackOverflow where the selected picture appears before uploading? I'm very new to this, so please be patient with me. Controller $scope.uploadFile = ...

Having trouble with getting datatables to work when trying to append data using AJAX posts?

https://i.sstatic.net/26XrD.png Hey there, I've been attempting to retrieve data from a database using AJAX posts but I'm facing some issues. The first column's data is splitting into other columns (member names are appearing in the image f ...