Todd Davis
Todd Davis

Reputation: 6033

Angular - $watch for $dirty on a form not working?

I am trying to watch for changes to a form using Angular 1.x. I am doing this so that I can display a warning if the user navigates away from the page before saving the data. I am able to $watch for form.$valid just fine, but form.$dirty just never fires. So to be clear, this works:

$scope.$watch('forms.editForm.$valid', function (newVal, oldVal) {
    // This is how we tell if there are unsaved form changes so we don't navigate away
    $scope.unsavedFormChanges = oldVal;
}, true);

And this doesn't:

$scope.$watch('forms.editForm.$dirty', function (newVal, oldVal) {
    // This is how we tell if there are unsaved form changes so we don't navigate away
    $scope.unsavedFormChanges = oldVal;
}, true);

Can anyone please enlighten me as to why I can't $watch $dirty, and if there is a backup plan for doing so? - Thanks

Upvotes: 1

Views: 2223

Answers (2)

nuander
nuander

Reputation: 1403

I couldn't get the watch to fire reliably on the form $dirty property, so I watched the model for changes instead and then checked the form dirty property like this

    $scope.$watch("$scope.data", function () {
        if ($scope.myform.$dirty) $rootScope.pageDirty = true;
    }, true);

Upvotes: 0

Todd Davis
Todd Davis

Reputation: 6033

After banging my head against the wall long enough, I think I've figured this out. It seems to be that $valid is an object, and $dirty is a value. And that's where that third parameter comes in. The "true" at the end of the $watch statement tells $watch what it is watching. True means it's an object, False means it's a value. That being said, this works:

$scope.$watch('forms.editForm.$dirty', function (value) {
    // This is how we tell if there are unsaved form changes so we don't navigate away
    $scope.unsavedFormChanges = value;
    $log.info('Form Dirty Changed: ' + value);
}, false);

I also changed the oldval/newval to just a value, since that's all we're getting.

Upvotes: 3

Related Questions