3

I have a simple angular form

<form name="myForm" ng-controller="myFormController"></form>

and need to call $setPristine() to myForm in myFormController. What is the best way to initialize this form as a $scope variable?

I tried $scope.myForm.$setPristine(); but it gave me:

Cannot read property '$setPristine' of undefined

Thanks in advance.


EDIT From the docs:

name (optional) Name of the form. If specified, the form controller will be published into related scope, under this name.

That means you can access it in a controller, but how?

0

3 Answers 3

2

form directive does publish the name of the form to the scope. But if the form is nested inside the ng-controller element, then the form's scope variable is not yet available when the controller function runs.

As an illustration:

<div ng-controller="OuterCtrl">
  <form name="form1">
    <div ng-controller="InnerCtrl"></div>
  </form>
</div>

The following would happen:

.controller("OuterCtrl", function($scope){
   // $scope.form1.$setPristine(); // this will fail
})
.controller("InnerCtrl", function($scope){
   $scope.form1.$setPristine(); // this will succeed
});

It is rarely needed to access the form when the controller function runs. Typically, it's done in response to some action, like a submit action. When that happens, the "OuterCtrl" will have $scope.form1:

.controller("OuterCtrl", function($scope){
   $scope.submitForm = function(){
      //... do something with form data
      $scope.form1.$setPristine();
   }
});

In that respect, $timeout would, in fact, work and would not cause race conditions. But you should re-examine why you need it the form when the controller function first runs.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this in your controller.

$timeout(function () {
   // here you should be able to access $scope.myForm
})

4 Comments

apart from not working in this case $timeout is never a good solution ;)
It worked for me. Can you please create a plunker/fiddle for this.
ngController will processed at priority:500, after which ngInit with priority:450, then form directive with the default priority, $timeout will guarantee the successful compilation of formDirective.
@DonJuwe, did this work for you? or did you found any other solution?
1

I just wasted some time dealing with this. In my case, I had the form shown a bit later using a ng-if. Changing the form conditions to an ng-show resolved the non-initialization of the $scope.myform.

1 Comment

I have the feeling I ran into similar issues before. But darn, yet again I fall into it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.