Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Tate Pultro
Tate Pultro
11,765 Points

Drop down not changing the date format dynamically

I've got my JS laid out exactly how it is in the video, however selecting a new format from the drop down doesn't change the formatting of a selected date in the datepicker. If I refresh the page and select the a new format before selecting a date, the date is displayed in the correct format.

Here's my code.

.directive('datepicker', function () {
    return {
      link: function ($scope, $element, $attrs) {
        var isInitialized = false;
        $attrs.$observe('datepickerFormat', function (newValue) {
          if (isInitialized) {
            $element.datepicker('option', 'dataFormat', newValue);
          } else if (newValue) {
            $element.datepicker({
              dateFormat: newValue
            });
            isInitialized = true;
          }
        });
      }
    }
  });

Thanks for any help.

1 Answer

In looking at the project code:

  .directive('datepicker', function () {
    return {
      require: 'ngModel',
      link: function ($scope, $element, $attrs, ngModelCtrl) {
        var initializedDatepicker = false;
        $attrs.$observe('datepickerFormat', function (newValue) {
          // If we've already initialized this, just update option
          if (initializedDatepicker) {
            $element.datepicker('option', 'dateFormat', newValue);
          // $observe is still called immediately, even if there's no initial value
          // so we check to confirm there's at least one format set
          } else if (newValue) {
            $element.datepicker({
              dateFormat: newValue,
              onSelect: function (date) {
                $scope.$apply(function () {
                  ngModelCtrl.$setViewValue(date);
                });
              }
            });
            initializedDatepicker = true;
          }
        });

        ngModelCtrl.$render = function () {
          $element.datepicker('setDate', ngModelCtrl.$modelValue);
        }
      }
    }

There appears to be some differences between what you have used and the source. Have you tried verifying it with the source code? Is your console returning any JS errors? I'm not the best with Angular but it looks like you are at least missing the onSelect which I would assume updates the new selected value?