Skip to content

Instantly share code, notes, and snippets.

@kswin
Created February 2, 2017 03:06
Show Gist options
  • Save kswin/6e523b0b123355420cb093090a3ca74e to your computer and use it in GitHub Desktop.
Save kswin/6e523b0b123355420cb093090a3ca74e to your computer and use it in GitHub Desktop.
ngModelController demo
angular
.module('App', ['ngMessages'])
.controller('AppController', ($scope) => {
$scope.date = moment();
})
.directive('dateDigits', () => ({
restrict: 'A',
require: 'ngModel',
link: (scope, elem, attr, ngModelController) => {
const monthDayYear = 'MM-DD-YYYY';
attr.placeholder = monthDayYear;
console.log('dateDigits init');
const monthDayYearParser = (viewValue) => {
console.log('monthDayYearParser called with: ', viewValue);
let parsed = moment(viewValue, monthDayYear, /*enables moment strict parsing*/ true);
if (viewValue) {
parsed = moment(viewValue, monthDayYear, /*enables moment strict parsing*/ true);
if (!parsed.isValid()) {
return undefined;
}
}
console.log('monthDayYearParser returns ', parsed);
return parsed;
};
const dateFormatter = (modelValue) => {
console.log('formatter called with: ', modelValue);
let result;
if (modelValue) {
result = modelValue.format(monthDayYear);
}
console.log('formatter returns', result);
return result;
};
const viewChangeListener = () => {
console.log('viewChangeListener called');
console.log('viewChangeListener - $viewValue', ngModelController.$viewValue);
console.log('viewChangeListener - $modelValue', ngModelController.$modelValue);
}
ngModelController.$validators.aValidator = (modelValue, viewValue) => {
console.log('aValidator called', modelValue, viewValue);
return true;
};
ngModelController.$viewChangeListeners.push(viewChangeListener);
ngModelController.$parsers.push(monthDayYearParser);
ngModelController.$formatters.push(dateFormatter);
}
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment