Created
February 2, 2017 03:06
-
-
Save kswin/6e523b0b123355420cb093090a3ca74e to your computer and use it in GitHub Desktop.
ngModelController demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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