import * as angular from 'angular' ; import { IDateParser } from './DateParser' ; export class DateParserDirective implements angular . IDirective { restrict = 'A' ; require = 'ngModel' ; scope = { ngModel : '=' } ; constructor ( private dateFilter , private $dateParser , private $locale ) { } link : angular . IDirectiveLinkFn = ( $scope , element , attrs , ngModel ) => { let dateFormat ; attrs . $observe ( 'dateParser' , ( value ) => { dateFormat = value ; ngModel . $render ( ) ; } ) ; $scope . $watchCollection ( ( ) => this . $locale , ( value , oldValue ) => { if ( ! angular . equals ( value , oldValue ) ) { ngModel . $render ( ) ; } } ) ; ngModel . $parsers . unshift ( ( viewValue ) => { let date = this . $dateParser ( viewValue , dateFormat ) ; ngModel . $setValidity ( 'date' , ! viewValue || angular . isDate ( date ) ) ; return date ; } ) ; ngModel . $render = ( ) => { let modelValueExists = ngModel . $modelValue === '' || ngModel . $modelValue === null || ngModel . $modelValue ; element . val ( modelValueExists ? this . dateFilter ( ngModel . $modelValue , dateFormat ) : undefined ) ; this . scope . ngModel = ngModel . $modelValue ; } ; ngModel . $formatters . push ( ( modelValue ) => { ngModel . $setValidity ( 'date' , ! modelValue || angular . isDate ( modelValue ) ) ; return angular . isDate ( modelValue ) ? this . dateFilter ( modelValue , dateFormat ) : '' ; } ) ; } ; static factory ( ) { let directive = ( dateFilter , $dateParser , $locale ) => new DateParserDirective ( dateFilter , $dateParser , $locale ) ; directive . $inject = [ 'dateFilter' , '$dateParser' , '$locale' ] ; return directive ; } }