Skip to content Skip to sidebar Skip to footer

In Angular, How To Get A Form In $scope In Controller?

Having these two files: HTML:
...
JS (inside the Angular controller): $scope.registrationForm.conf

Solution 1:

I recommend using the controller itself instead of the $scope provider for this. This was one of the first issues I came across when working with angularjs

In your controller:

functionMyController($scope) {
  var vm = this;
  vm.registrationForm.confirmPassword.$setValidity("PasswordsMatch", $scope.validation.doPasswordsMatch);
}

In your form:

<formname="vm.registrationForm"ng-submit="registerUser()">
   ...
</form>

The only gotcha is that you need to specify the controllerAs property in your route or ngInclude:

ng-include="templates/my-template.html" ng-controller="MyController as vm"

or

when('/my-route', {
  templateUrl: 'templates/my-template.html',
  controller: 'MyController as vm'
 })

Solution 2:

You need to add a name attribute to form element.

<formname="registrationForm"ng-submit="registerUser()">
   ...
</form>

Solution 3:

this form must rely on a controller indeed. please take a look at the example:

angular.module("fooApp",[]);

angular.module("fooApp")
  .controller("formctl",function(){
    this.user={};
    this.dosave=function(){
      if(this.user.pwd == this.user.confpwd)
        alert(this.user.username+" logged");
      elsealert("pwd does not match");
    };
  });
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script><divng-app="fooApp"><h1>sample</h1><divng-controller="formctl as ctl"><formng-submit="ctl.dosave()"><label>username</label><br/><inputng-model="ctl.user.username"required/><br/><label>password</label><br/><inputng-model="ctl.user.pwd"type="password"required/><br/><label>confirm password</label><br/><inputng-model="ctl.user.confpwd"type="password"/><br/><inputtype="submit"/></form></div></div>

Solution 4:

You'll want to pass the form into the submit function to pass the entire form into the controller. Use the form name.

<formname="registrationForm"ng-submit="registerUser(registrationForm)">
...
</form>

The other option would be to pass the inputs directly in as params

<form name="myForm" novalidate >
  some input: <inputtype="text" name="sometext" ng-model="myInput">
  <inputtype="submit" ng-click="doAction(myInput)">
</form>

Quick Plunk https://plnkr.co/edit/s0Al2LTHkvUPoLYNzTpm?p=info

If you're just after the value of the inputs, it's easier to test if you have explicit parameters that you expect on the method instead of dumping in the entire form.

Post a Comment for "In Angular, How To Get A Form In $scope In Controller?"