how to create an angular datepicker directive that uses ng-model

32,773

Solution 1

AngularJS actually provides a special controller for interacting with ngModel that you can use inside your directives; just add require: 'ngModel' to your directive definition.

This gives you a fourth paramter to your link function, which is the controller you asked for in require--in this case, an instance of ngModelController. It has a method called $setViewValue you 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

Solution 2

There may be a better way, but this will work:

http://jsbin.com/ufoqan/4/edit

app.directive('datepicker', function() {
  return {
    link: function(scope, el, attr) {
      $(el).datepicker({
        onSelect: function(dateText) {
          console.log(dateText);
          var expression = attr.ngModel + " = " + "'" + dateText + "'";
          scope.$apply(expression);
          console.log(scope.startDate);
          // how do i set this elements model property ?
        }
      });
    }
  };
});

You also asked why. The reason is that jquery happens outside the angular system. You can find more info here under the $apply method: docs

Share:
32,773

Related videos on Youtube

David
Author by

David

Updated on July 23, 2022

Comments

  • David
    David almost 2 years

    I have created an angular directive for my jQuery UI datepicker. The problem is that the directive doesn't update the input's ng-model when a date is selected. Any idea why?

    http://jsbin.com/ufoqan/1/edit

  • Florian F
    Florian F about 11 years
    Good answer. Note , there is an exisiting jquery UI datepicker here: github.com/angular-ui/ui-date Reading the source code will help understand how ngModelController works
  • Jonah
    Jonah about 11 years
    Very useful to know about. Thanks Brandon!