jQuery UI Calendar Datepicker in an Angular App with ng-init

If you’re building an app using AngularJS, I’m sure you’re like me and try to do everything with pure Angular, but sometimes you need to fall back on existing frameworks such as jQuery UI. This is probably more so in an Angular 1.7 app versus an app built using the latest Angular 6+ releases. So, in this post, we’ll take a quick look at how you can use the jQuery UI Datepicker widget in your Angular 1.7 app with the help of ng-init.

A Quick View of the Angular App Interface

Here’s a quick view of a sample interface (which is actually from a SharePoint app that I’m building) built with Angular 1.7.

Straightforward: the user tabs or clicks into the Start Date or End Date fields, the jQuery UI Calendar Datepicker widget renders the calendar, and when all fields are filled, the user saves the project.

What is the Problem

The problem you’ll face when trying to use the Datepicker widget in an AngularJS app is that it won’t render/function unless you ensure you register the handler after the DOM is completely built.

With the jQuery UI Datepicker, you bind your event handler to the HTML text input control as follows:

$(function() {$('#datepicker').datepicker();}); // straight from the documentation linked above

If you’ve worked with Angular and jQuery, you know that the timing of binding your handlers to DOM elements’ events often requires a bit of handholding with the use of $digest(), $watch(), and $apply(). This scenario is no exception: you need ensure the datepicker() handler is registered to the events on your HTML input element (i.e. serving as your calendar UI), otherwise it’s not going to be invoked when the events (e.g. change, mouseenter, etc.) fire.

But you don’t need to worry about using either of those AngularJS methods in this case.

What is the Fix

You don’t need a series of $watch() and $apply() calls here, fortunately. You only need the Angular ng-init function attribute. For example:

<input type="text" class="form-control" id="editProjectEndDate" name="editProjectEndDate" ng-model="editProject.ProjectEndDate" ng-init="applyPicker('editProjectEndDate')" ng-required="true" />

Then, in your Controller or Directive (based on your design):

$scope.applyPicker = function (id) {
    $_('#' + id).datepicker();

Hope that helps.



Categories: Angular, Apps, Software Development

Tags: , ,

Leave a Reply