Skip to content

Commit

Permalink
refactor(directive): Use ngModelController. to determie empty values
Browse files Browse the repository at this point in the history
Rather than hard coding specific values, this directive now delegates to the ngModelController to

determine whether or not a view or model value is considered empty.
  • Loading branch information
dalelotts committed Nov 14, 2016
1 parent 1182a1b commit b4c0fdb
Showing 1 changed file with 20 additions and 18 deletions.
38 changes: 20 additions & 18 deletions src/dateTimeInput.js
Expand Up @@ -38,30 +38,20 @@
// Behaviors
switch (modelType) {
case 'Date':
result = handleEmpty(dateParser)
result = dateParser
break
case 'moment':
result = handleEmpty(momentParser)
result = momentParser
break
case 'milliseconds':
result = handleEmpty(millisecondParser)
result = millisecondParser
break
default: // It is assumed that the modelType is a formatting string.
result = handleEmpty(stringParserFactory(modelType))
result = stringParserFactory(modelType)
}

return result

function handleEmpty (delegate) {
return function (viewValue) {
if (angular.isUndefined(viewValue) || viewValue === '' || viewValue === null) {
return null
} else {
return delegate(viewValue)
}
}
}

function dateParser (viewValue) {
return momentParser(viewValue).toDate()
}
Expand Down Expand Up @@ -115,7 +105,7 @@
var formatterFormats = [modelType].concat(inputFormats).filter(unique)

// Behaviors
controller.$parsers.unshift(dateTimeParserFactory(modelType, inputFormats, dateParseStrict))
controller.$parsers.unshift(handleEmpty(dateTimeParserFactory(modelType, inputFormats, dateParseStrict)))

controller.$formatters.push(formatter)

Expand All @@ -130,23 +120,35 @@
self.indexOf(value) === index
}

function handleEmpty (delegate) {
return function (viewValue) {
if (controller.$isEmpty(viewValue)) {
return null
}
return delegate(viewValue)
}
}

function validator (modelValue, viewValue) {
if (angular.isUndefined(viewValue) || viewValue === '' || viewValue === null) {
if (controller.$isEmpty(viewValue)) {
return true
}
return moment(viewValue, inputFormats, moment.locale(), dateParseStrict).isValid()
}

function formatter (modelValue) {
if (angular.isUndefined(modelValue) || modelValue === '' || modelValue === null) {
if (controller.$isEmpty(modelValue)) {
return null
}

if (angular.isDate(modelValue)) {
return moment(modelValue).format(displayFormat)
} else if (angular.isNumber(modelValue)) {
}

if (angular.isNumber(modelValue)) {
return moment.utc(modelValue).format(displayFormat)
}

return moment(modelValue, formatterFormats, moment.locale(), dateParseStrict).format(displayFormat)
}

Expand Down

0 comments on commit b4c0fdb

Please sign in to comment.