open datepicker on autofocus html5 input date field angularjs

Viewed 381

I'm trying to autofocus a date field in angularjs. I have written a directive for it and it's working fine but I'm running into a problem. The HTML5 date picker does not opens up until and unless I don't click on it's icon which is coming on the right side.

(function () {
  "use strict";

  angular
    .module("ctraUIComponents")
    .directive("inputAutoFocus", autoFocus);

  /**
   * @ngInject
   * @return {{restrict: string, link: autoFocusLink}}
   */
  function autoFocus ($timeout) {
    /**
     * @type {{restrict: string, link: autoFocusLink}}
     */
    var directive = {
      restrict: "A",
      link: autoFocusLink
    };

    return directive;

    /**
     * @ngInject
     * @param scope
     * @param element
     */
    function autoFocusLink (scope, element) {
      $timeout(function() {
        element[0].focus();
      });
    }
  }
})();

Can somebody please help me in figuring out on how to open the datepicker on autofocus and plus how to open the date picker when we click anywhere on the input field.

2 Answers

The native date picker (e.g., <input type="date">) has a method called showPicker() that will open the datepicker programmatically.

<div layout-gt-xs="row">
    <div flex-gt-xs>
      <h4>Opening the calendar when the input is focused</h4>
      <md-datepicker ng-model="ctrl.myDate" md-placeholder="Enter date" md-open-on-focus></md-datepicker>
    </div>
</div>



angular.module('MyApp', ['ngMaterial', 'ngMessages', 'material.svgAssetsCache']).controller('AppCtrl', function() {
  this.myDate = new Date();
  this.isOpen = false;
});

for more examples follow this Angular JS Material examples link

Related