Losing values due to custom $validator and getterSetter in AngularJS / UI Bootstrap

My objective is to create a UI Bootstrap datepicker with an input mask feature.

The datepicker directive only validates dates selected using the popup window and not dates manually typed in by the user. To address this, I researched how to implement custom validation for the text input.

I have successfully implemented all of this in my working Plunk example.

Here are the key components:

<!-- HTML -->
<span>Errors: {{myForm.myDate.$error}}</span>
<input 
    name="myDate"
    type="text" 
    class="form-control" 
    ng-class="{error: myForm.myDate.$invalid && myForm.myDate.$dirty}"
    datepicker-popup="MM/dd/yyyy" 
    ng-model="dt" 
    is-open="opened" 
    min-date="'09/01/2015'" 
    max-date="'11/11/2015'" 
    ng-required="true" 
    show-weeks="false"
    show-button-bar="false" />


// JavaScript
.controller('DatepickerDemoCtrl', function ($scope) {
  $scope.dt = undefined;

  $scope.open = function($event) {
    $scope.opened = !$scope.opened;
  };

  $scope.today = new Date();
})

.config(function($provide) {
  $provide.decorator('datepickerPopupDirective', function($delegate) {
    var directive = $delegate[0];
    var link = directive.link;

    directive.compile = function() {
      return function(scope, iEl, iAttrs, ctrls) {
        link.apply(this, arguments);

        // use custom validator to enforce date range on hand-entered text
        ctrls[0].$validators.inDateRange = function(modelValue, viewValue) {
          console.log(modelValue, viewValue);

          // use the ranges provided in the attributes for the validation
          var enteredDate = new Date(viewValue)
          ,   min = new Date(iAttrs.minDate)
          ,   max = new Date(iAttrs.maxDate);

          return ctrls[0].$isEmpty(modelValue) 
                 || (min <= enteredDate && enteredDate <= max);
        };

        // apply input mask to the text field
        iEl.mask('99/99/9999');
      };
    };

    return $delegate;
  });  
});

Now, I want to make a simple addition by adding a getterSetter to my input to perform some tasks on the value before saving it to the model.

I update the ng-model on my element, introduce ng-model-options to utilize the getterSetter, and define the actual getterSetter method.

<!-- HTML -->
ng-model="getSetDate" 
ng-model-options="{getterSetter: true}"

// JavaScript
$scope.getSetDate = function(val) {
  if(angular.isDefined(val)) {
    $scope.dt = val;
  } else {
    return val;
  }
};

However, even in this basic Plunk example featuring the getterSetter, an error is introduced even though the function does not perform any actions. If I:

  1. Enter an invalid date, for example, 09/10/2011
  2. Correct it to a valid date (via typing), for instance, 09/10/2015
  3. The value disappears

I am unable to determine why the simple addition of this getterSetter is causing the loss of the value. Should I be implementing this in a different manner?

Answer №1

It seems that the date picker does not currently support the getterSetter option in ng-model-options, but it is a feature that the developers plan to add in the future.

https://github.com/angular-ui/bootstrap/issues/4837

Additionally, I have created a plunk that demonstrates updating a secondary model using $watch. This may offer a similar functionality to what you were trying to achieve with the getterSetter option. Here's the code snippet you can add to your existing example:

  $scope.dt = undefined;
  $scope.newdt = undefined;

  $scope.$watch('dt', function(){
    if ($scope.dt) 
      $scope.newdt = $scope.dt;
  });

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

Using JQuery to automatically scroll and anchor to the bottom of a dynamically populated div, but only if the user doesn't

I am attempting to achieve the functionality of automatically scrolling to the bottom of a div with the ID #chat-feed. The overflow for this div is set to auto, and I want it to remain at the bottom unless a user manually scrolls up. If they do scroll up, ...

AngularJS - seamless navigation to url with hash symbol

Currently, I am in the process of developing a web application using a combination of AngularJS and Laravel. Everything seems to be working fine when I navigate through the URLs and links within the app. However, an issue arises when I try to directly inp ...

Livereload.js is failing to load due to an invalid address

Snippet from Gruntfile.js: connect: { options: { port: 4000, hostname: 'localhost', livereload: 4002 }, livereload: { options: { open: true, middleware: function (connect) { return [ connect.st ...

The autocomplete feature is not displaying the data in the Bootstrap modal, only the list is visible

Having trouble with autocomplete in the bootstrap modal. The search for a book only shows black dots. Any solutions to this issue? As shown in the image, I've attempted to use CSS z-index but the problem persists. https://i.sstatic.net/e1ga9.png publi ...

When the user clicks, display one div and conceal the others

https://codepen.io/leiacarts/pen/PoqRxNZ I need assistance with two specific tasks related to my website layout. Firstly, I am struggling to ensure that images displayed in the red sections remain constrained and automatically resize within the content di ...

I am looking to modify the dimensions of the grouped GridHelper through the graphical user interface

I'm having trouble resizing the grid using the GUI interface. How can I adjust its size? Here are the steps I followed to create it. let scene = new THREE.Scene(); scene.background = new THREE.Color(0x222222); let group = new THREE.Group(); scene.add ...

When implementing JWT for route authentication, the webpage remains frozen in one spot

Currently, I am in the process of making modifications to a project. The front-end is built using Vue 2.0 and the back-end utilizes Node.js Express. To ensure security, I have implemented the JWT approach by requiring authentication for all pages except th ...

Incorporated asynchronous functionality, struggling to integrate it into the code

Previously, I used to utilize the following code for handling state: //get state MyClass.prototype.getState = function(key) { var value; switch(this._options.type){ case "cookie": value = $.cookie(key); ...

Solving the Cross-Origin Resource Sharing problem in AngularJS

While using the http dependency in AngularJS and setting headers for CORS, I am encountering an error. Please check the console.log for more information on the error. The error message reads: "XMLHttpRequest cannot load . Response to preflight request doe ...

Activate radio button exclusively for admin user

My current application includes an admin panel with functions to manage users. I use a while loop in the form creation to display 3 user types: Admin, Manager, and User, which are pulled from a database. Admin Manager User This is how my HTML Form look ...

JavaScript allows you to merge two attributes of an object together

I currently have an object array stored in JavaScript. Here's an example: objArr = [{"FirstName":"John","LastName":"Doe","Age":35},{"FirstName":"Jane","LastName":"Doe","Age":32}] My goal is to transform this object array into a new format like the f ...

How to achieve horizontal auto-scrolling in an image gallery with jQuery?

Hey there, I'm currently working on an Image Gallery project. I have arranged thumbnails horizontally in a div below the main images. Take a look at this snapshot img. My goal is to have the thumbnails scroll along with the main pictures as the user ...

Tips for applying textures dynamically to MeshPhongMaterial?

When trying to apply a texture on a THREE.MeshPhongMaterial, the texture fails to load. Here's the code snippet: let earth_geometry = new THREE.SphereGeometry(450, 10, 10) let earth_material = new THREE.MeshPhongMaterial({ emissive: 0xffffff }) ...

Creating a custom table layout with JavaScript and jQuery

I've been grappling with a project for some time now, and I'm stuck on this particular issue. In my database, I have a table structured like this: ProjectName UserName SpentDays FirstProject User1 10 SecondProject User1 5 SecondProjec ...

Outputting PHP code as plain text with jQuery

My aim is to set up a preview HTML section where I am encountering a difficulty. I am struggling to display PHP code when retrieving and printing it from a textarea in the HTML. Here are my current codes, This is the HTML area where the textarea code will ...

Solving synchronization issues when updating and selecting MySql data in a Node.js environment with concurrent multiple requests

Currently, I'm using expressJS with an endpoint that connects to a MYSQL database. This endpoint executes a query to retrieve data and assigns the first result to a user by updating a specific field with the user ID. The rule is that each row can onl ...

What methods can be used to reveal the true value of data that has been encrypted?

Is it possible to retrieve the original value of data that has been hashed? Can the hashcode be reversed to reveal the real value of the data? String ida = new String(txtID.getText().toString()); int idb = ida.hashCode(); codeD.setText("result: " + ida) ...

Ensure that the HTML link is valid and authenticated using SESSIONS

When creating a website, one of the initial tasks I like to tackle is adding links at the bottom of the page for checking valid HTML and CSS: HTML5  •   CSS <div> <a href="http://validator.w3.org/check?uri=referer" ...

Sending the HTML input value to a Knockout view

Can someone assist me with a dilemma I'm facing? Within CRM on Demand, I have a view that needs to extract values from CRM input fields to conduct a search against CRM via web service. If duplicate records are found, the view should display them. Be ...

Displaying JSON data within a div section using Ajax and jQuery is not possible

I have generated a JSON in a specific format from an external PHP file: [ { "title": "Welcome!", "description": "The world has changed dramatically..", "image": "img/strawberry-wallpaper.jpg" } ] I am trying to use this data to populate a par ...