Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference angular ng-form from controller

Tags:

angularjs

How can I reference the ng-form object from within my controller?

I have

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

This code on the HTML page works fine

 {{myForm.$valid}}

returning true or false as the case may be.

But what I want is to check the status of the form from within a funciton in the controller, for example before posting the data or retrieving data.

I have tried

$scope.myForm.$valid

but this doesn't exist. Neither is there any reference to the myForm object in the $scope itself.

The ng-form is used within an ng-repeat, all of which is within a normal HTML form object which is why it is being used.

As I said, the myForm.$invalid is used to control the display/enabled controls within that form on the HTML page just fine.

Any ideas?

like image 740
DeclanMcD Avatar asked Jan 07 '15 09:01

DeclanMcD


People also ask

What is setPristine ()?

$setPristine();Sets the form to its pristine state. This method sets the form's $pristine state to true, the $dirty state to false, removes the ng-dirty class and adds the ng-pristine class. Additionally, it sets the $submitted state to false. This method will also propagate to all the controls contained in this form.

How do I access ngForm component?

In case you want to reference a directive like ngForm instead of the DOM element where the variable was declared, you simply need to set the value of the variable explicitly to the directive i.e #myForm="ngForm" . The component will be automatically added to your module by the Angular CLI.

Can I use NgModel in reactive forms?

You can use [(ngModel)] with Reactive forms. This will a completely different directive than the one that would be used without the formControlName . With reactive forms, it will be the FormControlNameDirective . Without the formControlName , the NgModel directive would be used.


1 Answers

one approach to check if a form is valid upon submitting will be to pass the myForm.$valid into the submit function:

<ng-form name="myForm" ng-submit="test(myForm.$valid, obj)">
  <input type="text" name="test" ng-model="obj.user" required>
  <input type="submit" ng-click="test(myForm.$valid, obj)" ng-disabled="!myForm.$valid">
</ng-form>

and the test function:

$scope.test = function($valid, obj) {
  if (!$valid) return;
  console.log(obj);
}

plnkr

like image 182
Nitsan Baleli Avatar answered Oct 04 '22 10:10

Nitsan Baleli