Reset form

Description

The following code shows how to reset form.

Example


<!doctype html>
<html ng-app="myApp" >
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
  <script>
var app = angular.module('myApp', []);
<!--from w  w  w  . j ava2s  . co  m-->
app.controller('MainCtrl', function($scope) {
  $scope.user = {
    email: 'j@example.com',
    firstName: 'XML',
    lastName: 'Javascript',
    websites: {
      url: 'www.java2s.com'
    },
    description: 'tutorial',
    password: 'mypass',
    admin: true
  };
  $scope.passwordRepeat = $scope.user.password;
  var original = angular.copy($scope.user);
  // Revert the user info back to the original
  $scope.revert = function() {
    $scope.user = angular.copy(original);
    $scope.passwordRepeat = $scope.user.password;
    $scope.userInfoForm.$setPristine();
  };  
  $scope.canRevert = function() {
    return !angular.equals($scope.user, original);
  };
  $scope.canSave = function() {
    return $scope.userInfoForm.$valid && !angular.equals($scope.user, original);
  };
  
});
  
  </script>
</head>
<body ng-controller="MainCtrl">
  <form name="userInfoForm">
    <label>E-mail</label>
    <input class="span6" type="email" name="email" ng-model="user.email" required unique-email>
    <label>Last name</label>
    <input class="span6" type="text" name="lastName" ng-model="user.lastName" required>
    <label>First name</label>
    <input class="span6" type="text" name="firstName" ng-model="user.firstName" required>
    <label>Password</label>
    <input class="span6" type="password" name="password" ng-model="user.password" required>
    <label>Password (repeat)</label>
    <input class="span6" type="password" name="passwordRepeat" ng-model="passwordRepeat" required>
    <label>Roles</label>
    <input type="checkbox" ng-model="user.admin"><span class="help-inline">Admin</span>
    <hr>
    <button ng-click="save()" ng-disabled="!canSave()">Save</button>
    <button ng-click="revert()" ng-disabled="!canRevert()">Revert Changes</button>
  </form>

  User Model: <pre>{{user|json}}</pre>
  Form: <pre>{{userInfoForm}}</pre>
  
</body>
</html>

Click to view the demo





















Home »
  AngularJS »
    AngularJS Example »




Controller
Directives
Expression
Filter
Form
Inject
Scope
Server
Style
Template
Utilities