I am building a dynamic form and am using the HTML5 date input for fields of type date. I was struggling to get the date input to display my date, and have come to the conclusion the value has to be a JavaScript date or the date will not display. If I am wrong on that, someone please correct me because it doesn't seem like it should be a requirement. Because my fields are dynamic I can't simply initialize specific fields to a Date, so I created a directive to convert to a JavaScript date.
angular.module( 'convertDate-directive', [] )
.directive('convertDate', function( $parse ) {
return {
restrict: "A",
link: function( scope, element, attrs ) {
var fieldModel = $parse( attrs.ngModel );
var fieldValue = fieldModel( scope );
fieldModel.assign( scope, new Date( fieldValue ) );
}
};
});
Here is my date input, which is rendered only if the field is of type date:
<input type="date"
ng-if="field.type == 'date'"
dynamic-model="field.name"
ng-model="field.name"
name="field.name"
max="{{field.maxValue | date : 'yyyy-MM-dd'}}"
min="{{field.minValue | date : 'yyyy-MM-dd'}}"
ng-required="field.required"
ng-model-options="{ updateOn: 'blur' }"
convert-date
class="form-control">
The problem with this directive is it triggers a $watch that I have on an object in my controller, which determines whether changes have been made and a save is needed.
My watch code:
$scope.$watch( 'application.' + resource.name, function( newValue, oldValue ) {
if ( newValue !== oldValue ) {
resource.changed = true;
}
}, true );
Is there any way to suppress the change event in this scenario? Or, is there a better way to initialize an HTML5 date field? Looking for ideas. Thanks!