Zbynek
Zbynek

Reputation: 5945

AngularJS: start watching for form change after form is compiled

I wish to watch if the form is pristine. My HTML looks like this:

 <div ng-if="ObservationCtrl.showHeader">
    <form class="form-horizontal" name="ObservationCtrl.observationForm" role="form" ng-if="!ObservationCtrl.doingResolve">
  {{ObservationCtrl.observationForm.$pristine}}
       <!-- SOME HTML -->
    </form>
 </div>

In my controller, I have following code:

    console.log(self.observationForm);

    $timeout(function(){
            $scope.$watch('self.observationForm', function() {
                if(self.observationForm) { 
                    console.log('form is valid? ', self.observationForm.$pristine); 
                } else {
                    console.log('form is not defined');
                }

            });
        },2000);

This logs undefined, but does the trick, since it starts watching form after 2 sec, when it already exists. However if I decrease the timeout to etc. 100, or even 0, then I get form is not defined message and when I change something in the form, the change is not recognized. According to some SO posts, that is because I start watching the form before it is compiled.

I wish to start watching the form after it is compiled. Relying on some predefined timeout is tricky, but I haven't found any other way to do that. I have also tried $evalAsync, but with no luck.

Upvotes: 0

Views: 67

Answers (1)

devqon
devqon

Reputation: 13997

The $scope does not know of the self property, you should change it to the "controller as" name. Also, you say you watch the $pristine property, so you should watch that one:

$scope.$watch('ObservationCtrl.observationForm.$pristine}', function(val) {
    console.log("Is pristine:", val);
});

Or you can change it to a function callback:

$scope.$watch(function() {
    return self.observationForm.$pristine;
}, function(val) {
    console.log("Is pristine:", val);
});

You can of course do checks if the form already exists, which in your case is because of the ng-if directive:

$scope.$watch(function() {
    if (self.observationForm) {
        return self.observationForm.$pristine;
    }

    return false;
}, function(val) {
    console.log("Is pristine:", val);
});

Upvotes: 1

Related Questions