CodesJava

Easy learning with example program codes

Angularjs form tutorial


Form:

Form act as a container for HTML elements.

Angularjs form:

AngularJS is very rich in form filling and validations. For example we can use ng-click to handle AngularJS click on button and use $dirty and $invalid flags to do the validations. Angularjs contains the form controls like input, select, button etc. These form elements use Angular events for events and validations handling.

Example Explanation:

First include the AngularJS library in the application. The ng-app directive initializes the application. The ng-controller directive defines the application controller named formCtrl. The formCtrl controller sets initial values to master object. It also contain reset() method which copies master object data to user object. The ng-model directive binds the input elements to the user object in the model. The ng-click directive calls reset() method when button is clicked.

Note: The novalidate attribute disables default browser validation if any.

Example:

<!DOCTYPE html>
<html>
<script 
 src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
<body>
 
<div ng-app="testApp" ng-controller="formCtrl">
  <form novalidate>
    First Name:<br>
    <input type="text" ng-model="user.firstName"><br>
    Last Name:<br>
    <input type="text" ng-model="user.lastName">
    <br><br>
    <button ng-click="reset()">RESET</button>
  </form>
  <p>form = {{user }}</p>
  <p>master = {{master}}</p>
</div>
 
<script>
var app = angular.module('testApp', []);
app.controller('formCtrl', function($scope) {
    $scope.master = {firstName:"Nidhi", lastName:"Gupta"};
    $scope.reset = function() {
        $scope.user = angular.copy($scope.master);
    };
    $scope.reset();
});
</script>
 
</body>
</html>

Try it:

JS Bin on jsbin.com

Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki