Using the md-date-picker along with the md-menu component

Whenever I try to click on the md-date-picker inside md-menu, it unexpectedly closes. You can view the issue on this CodePen link. This seems to be a bug related to ng-material as discussed in this GitHub issue. Any suggestions for a workaround?

Here is the HTML:

<div class="md-menu-demo menudemoBasicUsage" ng-controller="BasicDemoCtrl as ctrl" ng-app="MyApp">

  <div class="menu-demo-container" layout-align="center center" layout="column">
    <h2 class="md-title">Month Select</h2>
    <p>Select a month by clicking the input</p>
    <md-menu>

      <input md-menu-origin="" aria-label="Open phone interactions menu" ng-focus="ctrl.openMenu($mdOpenMenu, $event)" ng-model="ctrl.selectedMonth">
      <md-menu-content width="4" ng-click="$event.stopPropagation()">
<md-datepicker ng-model="dateFilter" md-placeholder="Till date" md-min-date="dateFilter.fromDate"></md-datepicker>
      </md-menu-content>
    </md-menu>
  </div>
</div>

And here is the JS:

angular
  .module('MyApp')
  .controller('BasicDemoCtrl', function DemoCtrl($mdDialog) {
    var originatorEv;

    this.openMenu = function($mdOpenMenu, ev) {
      originatorEv = ev;

          $mdOpenMenu(ev);
        };

        this.setMonth = function(val) {
          this.month = val;
          this.setSelectedMonth();
        };

        this.notificationsEnabled = true;
        this.toggleNotifications = function() {
          this.notificationsEnabled = !this.notificationsEnabled;
        };

        this.nextYear = function() {
          this.year++;
          this.setSelectedMonth();

        };

        this.preYear = function() {
          this.year = this.year - 1;
          this.setSelectedMonth();
        };
        
}).directive('stopEvent', function() {
        return {
          restrict: 'A',
          link: function(scope, element, attr) {
            if (attr && attr.stopEvent)
              element.bind(attr.stopEvent, function(e) {
                e.stopPropagation();
              });
          }
        };
      });

Answer №1

I managed to come up with a working solution, although it may not be the most optimal.

HTML:
<md-datepicker id="myDatePicker"
    ng-model="dateFilter" 
    md-placeholder="Till date" 
    md-min-date="dateFilter.fromDate">
</md-datepicker>

JS:
function setupDateButton()
{
    var dateButtonFix = document.getElementById("myDatePicker").children;
    for (var i = 0; i < dateButtonFix.length; i++)
    {
        if (dateButtonFix[i].tagName == 'BUTTON' || dateButtonFix[i].tagName == 'DIV')
        {
            if (dateButtonFix[i].tagName == 'DIV')
            {
                var child2 = dateButtonFix[i].children;
                for (var j = 0; j < child2.length; j++)
                {                               
                    if (child2[j].tagName == 'BUTTON')
                    {
                        child2[1].setAttribute("md-prevent-menu-close", "md-prevent-menu-close");
                    }
                }
             }
             else
                 dateButtonFix[0].setAttribute("md-prevent-menu-close", "md-prevent-menu-close");
         }
    }    
}    
setupDateButton();

There must be a more efficient way to achieve this functionality, but for now, it gets the job done.

Answer №2

Recently, I encountered the same issue and developed a specialized directive to address it.

Below is the code for my custom directive:

const TRUE = 'true';
const PREVENT_CLOSE = 'md-prevent-menu-close';

class CalendarBtnFixDirective {
  constructor() {
    this.restrict = 'C';
    this.require = '^^mdDatepicker'
  }

  link(scope, element, attrs, datePickerCtrl) {
    const nativeElement = element[0];
    const preventMenuClose = datePickerCtrl.$attrs.mdPreventMenuClose;

    if ([TRUE, PREVENT_CLOSE].indexOf(preventMenuClose) !== -1) {
      nativeElement.setAttribute(PREVENT_CLOSE, PREVENT_CLOSE);
    }
  }
}

export const MdCalendarFixModule = angular
  .module('md.calendar.fix.module', [])
  .directive('mdDatepickerTriangleButton', () => new CalendarBtnFixDirective())
  .name;

You can now utilize the md-prevent-menu-close attribute in your md-datepicker

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 enable a visible bootstrap tab to be clicked more than once?

Is there a way to override the default behavior on bootstrap tabs that prevents clicking on the currently shown tab? I need the user to be able to click on the tab again even if it is already active, as I am using AJAX to load content and reloading the pag ...

How to Properly Implement app.use() in Express for Middleware

What is the reason behind some middleware functions being passed in with invocation parentheses, while an anonymous function is passed in without being invoked? app.use(logger()); app.use(bodyParser()); If logger() is evaluated immediately and the return ...

Validating dates with JavaScript from the start date to the end date

I need to validate the from and to date fields using the date format d/m/Y H:i. This is what my code looks like: var startDate = new Date($('#fromdate').val()); var endDate = new Date($('#todate').val()); if (endDate.getTi ...

Creating a structure for data in Ruby on Rails to facilitate AJAX calls to controller actions

I am in need of a button on my website that can send data to the create action of a controller named "pagetimes". The functionality seems to be partially working, but it is not sending all the specified data. This issue may be due to my inability to struct ...

Can someone please help me convert this jQuery code into vanilla JavaScript?

My Cordova app has an email sending function that utilizes jQuery. During debugging, the ajax function works perfectly in my browser, but once I build the app and test it on my phone, it stops working. I encountered a similar issue before, which was resolv ...

Master the art of zeroing in on your drawing once it's complete

Please review the Demo and provide instructions on how to enhance the zoom function for Google Maps after the map is drawn. let map; let drawingManager; $(document).ready(function () { const latlng = new google.maps.LatLng(49.241943, -122.889318); ...

What is the best way to trigger an AngularJS function after a row selection event in Django?

In order to display the selected row id when a row selection event takes place in the datatable worklist, I am attempting to achieve this using an AngularJS function shown below: function showSelectedRowId($scope){ var dtWorklist = datatable_work ...

Singleton pattern for iFrames sharing the same origin

I have developed a web application that runs on multiple iframes within a parent window, similar to a modified version of GWT. Rather than each individual iframe accessing our backend service separately, I am attempting to have them share the data service ...

Guide to sorting data by the status value within a JavaScript object?

I have a JavaScript object structured like this: { "3": { "id": 3, "first": "Lisa", "last": "Morgan", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bbd7d6d4c9dcdad5fbdcd6dad2d795d8d4d6">[email&# ...

The functionality of making Slim POST requests is currently not functioning as expected within the Ionic

An issue is arising with my app that makes calls to a REST API using POST and GET methods. The app I'm developing with Ionic works perfectly when emulated using the command: ionic serve --lab However, when running the app on an actual device, calls ...

Customize your Vue 3 application with custom Axios functions for handling GET, PUT,

I am looking to enhance my use of axios by customizing the get, post, and put functions. After performing the axios.create() operation, I want every subsequent get operation to include a then and catch block. import axios from "axios"; export de ...

The final thumbnail fails to appear in the visible display (react-responsive-carousel)

I am currently facing an issue with displaying a series of images using react-responsive-carousel. When the images exceed a certain size causing the thumbnail section to become scrollable, the last thumbnail is always out of view. Although I have impleme ...

execute function once eventlistener completes running

I've implemented a code snippet to detect the availability of a gyroscope for user interaction. Here's how it works: function check_user_hardware(){ window.addEventListener("devicemotion", function(event){ if(event.rotationRate.alpha ...

Reduce the file size of CSS and JS files for Magento

We are facing an issue with minifying CSS and Javascript for our Magento website. Currently, the size of our website is 1.1 MB and we aim to reduce it to 1 MB or even lower if possible. I tried using the "CSS Settings" and "Javascript Settings" functions ...

Checking the authenticity of Javascript Objects containing date values

What is the best way to validate a JavaScript Object that includes date fields? While there are JSON validators such as tv4 that can check the format of string dates, our business logic operates with JavaScript Date instances which these validators do not ...

The latest version of Material UI, v4, does not currently support React 18

Looking to incorporate MUI (Material UI) into my website design. Encountering difficulties with installing this library, receiving the error message below: -npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While ...

Passing Data to a Different Route in Vue.js

Being new to Vue.js, I have a question on how to efficiently handle data retrieval from my backend application. Here is the code snippet that fetches all the data: var app2 = new Vue({ delimiters: ['%%', '%%'], el: '#app2& ...

Node.js SQLite3 - DB.each() not running the subsequent code block

When running the code snippet below, I am getting the following output: var db = new sqlite3.Database("database.sqlite") console.log("2") db.each("SELECT * FROM gban WHERE id = '"+id+"'", async functi ...

When you hover over an image, its opacity will change and text will overlay

I am looking for a way to decrease the opacity and overlay text on a thumbnail image when it is hovered over. I have considered a few methods, but I am concerned that they may not be efficient or elegant. Creating a duplicated image in Photoshop with the ...

Searching for the perfect jQuery regex to validate date formats

In my application, there is an input box that allows users to enter a string date like "today" or "tomorrow". However, I am facing a new challenge now - dates such as "3 march" or "8 january." The input box includes a dropdown menu feature where users can ...