ng-form

Description

We use ng-form to nest a form within another form. The outer form is valid when all of the child forms are valid.

The following code shows how to ng-form.

Example


<!--from  w  w w.j  a v  a 2 s  .co m-->

<!doctype html>
<!--
Created using JS Bin
http://jsbin.com

Copyright (c) 2014 by auser (http://jsbin.com/UduNeCA/1/edit)

Released under the MIT license: http://jsbin.mit-license.org
-->
<html ng-app="myApp">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js"></script>
<style id="jsbin-css">
input.ng-invalid {
  border: 1px solid red;
}

input.ng-valid {
  border: 1px solid green;
}
</style>
</head>
<body>
  
<form name="signup_form" ng-controller="FormController" ng-submit="submitForm()" novalidate>
  <div ng-repeat="field in fields" ng-form="signup_form_input">
    <input type="text"
           name="dynamic_input"
           ng-required="field.isRequired"
           ng-model="field.name"
           placeholder="{{field.placeholder}}" />
    <div ng-show="signup_form_input.dynamic_input.$dirty && signup_form_input.dynamic_input.$invalid">
      <span class="error" ng-show="signup_form_input.dynamic_input.$error.required">The field is required.</span>
    </div>
  </div>
  <button type="submit" ng-disabled="signup_form.$invalid">Submit All</button>
</form>
  
<script id="jsbin-javascript">
angular.module('myApp', [])
.controller('FormController', function($scope) {
  $scope.fields = [
    {placeholder: 'Username', isRequired: true},
    {placeholder: 'Password', isRequired: true},
    {placeholder: 'Email (optional)', isRequired: false}
  ];

  $scope.submitForm = function() {
    console.log("it works!");
  };
});
</script>
</body>
</html>
The following  CSS classes are set automatically, depending on the validity of the form:

ng-valid when form is valid
ng-invalid when form is invalid
ng-pristine when form is pristine
ng-dirty when form is dirty

To specify which method to call when submitting form, use one of the
following two directives:

ng-submit on the form element
ng-click on the first button or input field of type submit (input[type=submit])

Click to view the demo





















Home »
  AngularJS »
    AngularJS Tutorial »




Introduction
Buildin Filters
Buildin Directives