Home / Angular / AngularJs Datepicker Directive

AngularJs Datepicker Directive

AngularJS actually provides a special controller for interacting with thatngModel you can use inside your directives; just add torequire: 'ngModel' your function your directive definition.This gives you a fourth your function parameter to,link which is the controller you asked for in require–in this case, an instance of ngModelController. It has a method called $setViewValueyou can use to set the value of the model:

app.directive('datepicker', function() {
  return {
    require: 'ngModel',
    link: function(scope, el, attr, ngModel) {
      $(el).datepicker({
        onSelect: function(dateText) {
          scope.$apply(function() {
            ngModel.$setViewValue(dateText);
          });
        }
      });
    }
  };
});

The beautiful thing about ngModelController is it automatically takes care of validation and formatting (in the case of a specific input type) and integration with things like ngChange callbacks; check out this example: http://jsbin.com/ufoqan/6/edit

About Mohammad Fareed

Software Engineer @ Tekzenit.

Check Also

What’s new In Angular 5? What Is the Difference Between Angular 4 and Angular 5?

Angular, one of the best open-source JavaScript frameworks for web application development, recently upgraded with …

Leave a Reply

Your email address will not be published. Required fields are marked *