Mastering Web Application

(Rick Simeone) #1

Building Your Own Directives


Here, we check that model changes get forwarded to the widget and widget
changes get passed back to the model. Notice that we do not call $digest() after
selectDate(), since it is the directive's job to ensure that the digest occurs after a
user interaction.


There are more tests for all different scenarios for this directive.
They can be found in the sample code.

Implementing the jQuery datepicker directive


The directive implementation is again making use of the functionality provided
by the ngModelController. In particular, we add a function to the $formatters
pipeline that ensures that the model is a Date object, we add our onSelect callback
to the options, and we override the $render function to update the widget when
the model changes.


myModule.directive('datePicker', function () {
return {
require:'ngModel',
link:function (scope, element, attrs, ngModelCtrl) {
ngModelCtrl.$formatters.push(function(date) {
if ( angular.isDefined(date) &&
date !== null &&
!angular.isDate(date) ) {
throw new Error('ng-Model value must be a Date object');
}
return date;
});

var updateModel = function () {
scope.$apply(function () {
var date = element.datepicker("getDate");
element.datepicker("setDate", element.val());
ngModelCtrl.$setViewValue(date);
});
};
var onSelectHandler = function(userHandler) {
if ( userHandler ) {
return function(value, picker) {
updateModel();
return userHandler(value, picker);
};
Free download pdf