Forms - AngularJS
AngularJS provides great way to create Forms which submit their data without postback.
AngularJS Forms use two directives:
- ng-model: The ng-model directives is used for binding input controls to Javascript Objects.
- ng-submit: Bind AngularJS Controller submit function to submit event of HTML Form. It also prevents the form to submit to server directly.
AngularJS Form Example
<html> <head> <title>AngularJS Form Example</title> </head> <body ng-app="testApp" ng-controller="mainCtrl"> <form ng-submit="submit1()"> <p> Enter First Name: <input type="textbox" ng-model="user.firstName" /> </p> <p> Enter Last Name: <input type="textbox" ng-model="user.lastName" /> </p> <p> <input type="submit" value="Submit" /> </p> </form> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js" ></script> <script> var app = angular.module('testApp', []); app.controller('mainCtrl', ['$scope', function($scope){ $scope.user = {}; $scope.user.firstName = ""; $scope.user.lastName = ""; $scope.submit1 = function() { console.log('FirstName: ' + $scope.user.firstName); console.log('LastName: ' + $scope.user.lastName); }; }]); </script> </body> </html>
Result:
- In line 6 defines an testApp application using ng-app directive.
- In line 6 defines an mainCtrl controller using ng-controller directive.
- In line 7 defines a HTML form and ng-submit directive which bind to submit1() function of mainCtrl controller.
- In line 9 bind the input textbox control to firstName property of user object using ng-model directive.
- In line 11 bind the input textbox control to lastName property of user object using ng-model directive.
- In line 15 defines a submit input control which call the submit function of mainCtrl controller.
- In line 21 defines an AngularJS app 'testApp' using angular.module function.
- In line 23 defines an AngularJS controller 'mainCtrl' using app.controller function.
- In line 24 defines a user javascript object.
- In line 25,26 create two properties firstName and lastName into user object.
- In line 27 defines a submit function that print the firstName and lastName of user object into console.