Mastering Web Application

(Rick Simeone) #1

Building Your Own Directives


Function Description
element.datepicker(options) Create a new widget using the given
options and attach it to the element.
element.datepicker("setDate", date) Set the date on the widget.
element.datepicker("getDate") Get the date on the widget.
element.datepicker("destroy") Destroy and remove the widget from
the element.

We want to be informed when the user selects a new date with the picker. The
options that we pass to create a new widget can provide an onSelect callback that
will be called when the user selects a date:


element.datepicker({onSelect: function(value, picker) { ... });

To keep things simple, we will specify that the datepicker directive
can only be linked to a JavaScript Date object in the model.

The general pattern for wrapping JQuery input widgets is similar, again, to building
a validation directive. You require ngModel and place functions on the $parsers and
$formatters pipeline to transform the values between the model and the view.


Also, we need to put data into the widget when the model changes and get data
into the model when the widget changes. We override ngModel.$render() to
update the widget. This function is called after all the $formatters have been
executed successfully. To get the data out, we use the onSelect callback to call
ngModel.$setViewValue(), which updates the view value and triggers the
$parsers pipeline.


Scope

someDate
$render

$setViewValue onSelect
setDate

jQueryUI
Datepicker
click

$formalities

$parsers

ngModelController

Writing tests for directives that wrap libraries


In a pure unit test we would create a mock jQueryUI datepicker widget that
exposes the same interface. In this case we are going to take a more pragmatic
approach and use a real datepicker widget in the tests.

Free download pdf