user1732364 user1732364 - 3 months ago 21
AngularJS Question

Angular ng-dirty not toggling with datepicker directive

I have a custom directive for applying jQuery UI Datepicker to some inputs. I can pick a date and it updates the input. However, when i post back the results. The input(control) that was edited isn't marked dirty so the changes never get saved. See below..

<td>
<input type="text" jqdatepicker name="Delegation.StartDate" ng-model="delegation.StartDate" />
</td>
<td>
<input type="text" jqdatepicker name="Delegation.EndDate" ng-model="delegation.EndDate" />
</td>

App.directive('jqdatepicker', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
element.datepicker({
dateFormat: 'm/dd/yy',
onSelect: function (date) {
scope.date = date;
scope.$apply();
ngModelCtrl.$setDirty(); <--doesn't work
}
});
}
};});


I have tried using scope, element, ngModel and can't get the state of the control to change from pristine to dirty. On save, i scrap the rows(tr) for those that have the class ng-dirty and process them. Any thoughts on how to do this? I use the same method on about 8 other pages without issue but those do not use the directive/datepickers.

Answer

After lots of trial and error and reading. I finally got it to work! Below is the directive.

App.directive('jqdatepicker', function () {
return {
    restrict: 'A',
    require: 'ngModel',
    link: function (scope, element, attrs, ngModelCtrl) {
        element.datepicker({
            dateFormat: 'm/dd/yy',
            onSelect: function (date) {
                console.log(ngModelCtrl);
                ngModelCtrl.$setViewValue(date);
            }
        });
    }
};

});