Skip to content

Instantly share code, notes, and snippets.

@wehrhaus
Created January 20, 2016 17:32
Show Gist options
  • Save wehrhaus/f4fef8d188301cc07a20 to your computer and use it in GitHub Desktop.
Save wehrhaus/f4fef8d188301cc07a20 to your computer and use it in GitHub Desktop.
Directive Example using setValidation
(function() {
'use strict';
angular
.module('jpmTool.components')
.directive('datePicker', datePicker);
function datePicker() {
return {
scope: {
inputLabel: '=',
inputName: '=',
maskConfigInput: '=',
maskConfigPlaceholder: '=',
inputModel: '=',
inputValidation: '=',
validationMessage: '='
},
require: 'ngModel',
replace: true,
restrict: 'E',
bindToController: true,
controller: datePickerCtrl,
controllerAs: 'ctrl',
templateUrl: 'templates/components/date-picker/date-picker.html'
};
}
/**
* @ngInject
*/
function datePickerCtrl(
$filter,
$scope,
$timeout,
constants,
moment,
_
) {
var ctrl = this;
var dateFormat = 'MM/DD/YYYY';
var datePicker;
// instantiate datePicker once module is loaded
$timeout(function() {
datePicker = $scope.datePicker;
});
/**
*
* @type {{obj: Date, str}}
*/
ctrl.asOfVal = {
obj: moment(ctrl.inputModel).toDate(),
str: ctrl.inputModel,
originalStr: ctrl.inputModel
};
/**
*
* @param {string} direction
*/
ctrl.blur = function(direction) {
if (direction === 'fromDate') {
ctrl.isInvalid = !ctrl[ctrl.inputValidation](ctrl.asOfVal.obj);
ctrl.asOfVal.str = moment(ctrl.asOfVal.obj).format(dateFormat);
} else {
ctrl.isInvalid = !ctrl[ctrl.inputValidation](ctrl.asOfVal.str);
ctrl.asOfVal.obj = moment(ctrl.asOfVal.str).toDate();
}
ctrl.updateValidityClasses();
datePicker[ctrl.inputName].$setDirty();
ctrl.inputModel = ctrl.asOfVal.str;
};
/**
* Sets the input to either ng-valid or ng-invalid
*/
ctrl.updateValidityClasses = function() {
datePicker[ctrl.inputName].$setValidity('date', !ctrl.isInvalid);
ctrl.enableDisableContinue(ctrl.isInvalid);
};
/**
* Handle form next button state
*/
ctrl.enableDisableContinue = function(invalid) {
angular.element('.next-button').attr('disabled', invalid);
};
/**
* Ensures a date range falls between the current date and the constanst.validation.priceStalePeriod
*
* @param val
* @returns {boolean}
*/
ctrl.validationValueAsOf = function(val) {
var viewValue = moment(val).format(dateFormat);
if (_.isEmpty(viewValue)) {
return true;
}
var tomorrow = moment().add(1, 'days'); // moment.isBetween is exclusive
var staleDate = moment().subtract(constants.validation.priceStalePeriod + 1, 'days');
var valueAsOf = moment(viewValue, dateFormat, true);
if (valueAsOf.isValid() && valueAsOf.isBetween(staleDate, tomorrow, 'day')) {
return true;
}
return false;
};
/**
*
* @type {boolean}
*/
ctrl.isInvalid = !ctrl[ctrl.inputValidation](ctrl.asOfVal.str);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment