skaterdav85 skaterdav85 - 6 months ago 37
AngularJS Question

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

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?


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) {
        onSelect: function(dateText) {
          scope.$apply(function() {

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: