Search code examples
angularjsangularjs-scopeangularjs-controller

How to initialize form as scope variable in controller


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?


Solution

  • 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.