Nested Forms – AngularJS

Nested Forms provides a great way to apply grouping of form controls.

Because HTML does not allow you to nest forms so AngularJS provides support for nested forms using ng-form directive.

Nested Forms is useful for creating grouping of form controls so that their validition can be implemented separately.

Nested Forms Example

<title>AngularJS Nested Form Example</title>
<body ng-app="testApp" ng-controller="mainCtrl">
	<form ng-submit="submit()" name="myForm">
			Enter First Name: <input type="textbox" ng-model="user.firstName" />
			Enter Last Name: <input type="textbox" ng-model="user.lastName" />
		<ng-form name="profile">
			<h2>Personal Information</h2>
				Address 1: <input type="textbox" ng-model="user.profile.addr1" />
				Address 2: <input type="textbox" ng-model="user.profile.addr2" />
			<input type="submit" value="Submit" />
	<script src="" ></script>
	var app = angular.module('testApp', []);
	app.controller('mainCtrl', ['$scope', function($scope){
		$scope.user = { firstName: '', lastName: ''};
		$scope.user.profile = { addr1: "", addr2: ""};
		$scope.submit = function()
			console.log('FirstName: ' + $scope.user.firstName);
			console.log('LastName: ' + $scope.user.lastName);
			console.log('personal information');
			console.log('Address 1: ' + $scope.user.profile.addr1);
			console.log('Address 2: ' + $scope.user.profile.addr2);



  • Line 6 defines a AngularJS applicatino ‘testApp’ using ng-app directive.
  • Line 6 defines a ‘mainCtrl’ AngularJS controller using ng-controller directive.
  • Line 7 defines a HTML form name ‘myForm’ and bind submit() function to mainCtrl controller using ng-submit directive.
  • Line 9,12 binds the input controls to firstName and lastName properties of user javascript object.
  • Line 14 defines a nested form using ng-form directive name ‘profile’.
  • Line 17, 18 binds the input controls to addr1, addr2 to profile object of user.
  • Line 24 defines a submit button.
  • Line 30 defines a new module ‘testApp’ using angular.module function.
  • Line 32 defines a AngularJS controller ‘mainCtrl’.
  • Line 33 declare a user javascript object with two properties firstName, lastName.
  • Line 34 declare a profile property of user object with two properties addr1 and addr2.
  • Line 36 defines a submit button which show properties of user and profile objects in console.