EVOLUTION-MANAGER
Edit File: forms.html
<a href='https://github.com/angular/angular.js/edit/v1.3.x/docs/content/guide/forms.ngdoc?message=docs(guide%2FForms)%3A%20describe%20your%20change...' class='improve-docs btn btn-primary'><i class="glyphicon glyphicon-edit"> </i>Improve this Doc</a> <p>Controls (<code>input</code>, <code>select</code>, <code>textarea</code>) are ways for a user to enter data. A Form is a collection of controls for the purpose of grouping related controls together.</p> <p>Form and controls provide validation services, so that the user can be notified of invalid input. This provides a better user experience, because the user gets instant feedback on how to correct the error. Keep in mind that while client-side validation plays an important role in providing good user experience, it can easily be circumvented and thus can not be trusted. Server-side validation is still necessary for a secure application.</p> <h1 id="simple-form">Simple form</h1> <p>The key directive in understanding two-way data-binding is <a href="api/ng/directive/ngModel">ngModel</a>. The <code>ngModel</code> directive provides the two-way data-binding by synchronizing the model to the view, as well as view to the model. In addition it provides an <a href="api/ng/type/ngModel.NgModelController">API</a> for other directives to augment its behavior.</p> <p> <div> <a ng-click="openPlunkr('examples/example-example31')" class="btn pull-right"> <i class="glyphicon glyphicon-edit"> </i> Edit in Plunker</a> <div class="runnable-example" path="examples/example-example31" module="formExample"> <div class="runnable-example-file" name="index.html" language="html" type="html"> <pre><code><div ng-controller="ExampleController"> <form novalidate class="simple-form"> Name: <input type="text" ng-model="user.name" /><br /> E-mail: <input type="email" ng-model="user.email" /><br /> Gender: <input type="radio" ng-model="user.gender" value="male" />male <input type="radio" ng-model="user.gender" value="female" />female<br /> <input type="button" ng-click="reset()" value="Reset" /> <input type="submit" ng-click="update(user)" value="Save" /> </form> <pre>form = {{user | json}}</pre> <pre>master = {{master | json}}</pre> </div> <script> angular.module('formExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.master = {}; $scope.update = function(user) { $scope.master = angular.copy(user); }; $scope.reset = function() { $scope.user = angular.copy($scope.master); }; $scope.reset(); }]); </script></code></pre> </div> <iframe class="runnable-example-frame" src="examples/example-example31/index.html" name="example-example31"></iframe> </div> </div> </p> <p>Note that <code>novalidate</code> is used to disable browser's native form validation.</p> <p>The value of <code>ngModel</code> won't be set unless it passes validation for the input field. For example: inputs of type <code>email</code> must have a value in the form of <code>user@domain</code>.</p> <h1 id="using-css-classes">Using CSS classes</h1> <p>To allow styling of form as well as controls, <code>ngModel</code> adds these CSS classes:</p> <ul> <li><code>ng-valid</code>: the model is valid</li> <li><code>ng-invalid</code>: the model is invalid</li> <li><code>ng-valid-[key]</code>: for each valid key added by <code>$setValidity</code></li> <li><code>ng-invalid-[key]</code>: for each invalid key added by <code>$setValidity</code></li> <li><code>ng-pristine</code>: the control hasn't been interacted with yet</li> <li><code>ng-dirty</code>: the control has been interacted with</li> <li><code>ng-touched</code>: the control has been blurred</li> <li><code>ng-untouched</code>: the control hasn't been blurred</li> <li><code>ng-pending</code>: any <code>$asyncValidators</code> are unfulfilled</li> </ul> <p>The following example uses the CSS to display validity of each form control. In the example both <code>user.name</code> and <code>user.email</code> are required, but are rendered with red background only after the input is blurred (loses focus). This ensures that the user is not distracted with an error until after interacting with the control, and failing to satisfy its validity.</p> <p> <div> <a ng-click="openPlunkr('examples/example-example32')" class="btn pull-right"> <i class="glyphicon glyphicon-edit"> </i> Edit in Plunker</a> <div class="runnable-example" path="examples/example-example32" module="formExample"> <div class="runnable-example-file" name="index.html" language="html" type="html"> <pre><code><div ng-controller="ExampleController"> <form novalidate class="css-form"> Name: <input type="text" ng-model="user.name" required /><br /> E-mail: <input type="email" ng-model="user.email" required /><br /> Gender: <input type="radio" ng-model="user.gender" value="male" />male <input type="radio" ng-model="user.gender" value="female" />female<br /> <input type="button" ng-click="reset()" value="Reset" /> <input type="submit" ng-click="update(user)" value="Save" /> </form> </div> <style type="text/css"> .css-form input.ng-invalid.ng-touched { background-color: #FA787E; } .css-form input.ng-valid.ng-touched { background-color: #78FA89; } </style> <script> angular.module('formExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.master = {}; $scope.update = function(user) { $scope.master = angular.copy(user); }; $scope.reset = function() { $scope.user = angular.copy($scope.master); }; $scope.reset(); }]); </script></code></pre> </div> <iframe class="runnable-example-frame" src="examples/example-example32/index.html" name="example-example32"></iframe> </div> </div> </p> <h1 id="binding-to-form-and-control-state">Binding to form and control state</h1> <p>A form is an instance of <a href="api/ng/type/form.FormController">FormController</a>. The form instance can optionally be published into the scope using the <code>name</code> attribute.</p> <p>Similarly, an input control that has the <a href="api/ng/directive/ngModel">ngModel</a> directive holds an instance of <a href="api/ng/type/ngModel.NgModelController">NgModelController</a>. Such a control instance can be published as a property of the form instance using the <code>name</code> attribute on the input control. The name attribute specifies the name of the property on the form instance.</p> <p>This implies that the internal state of both the form and the control is available for binding in the view using the standard binding primitives.</p> <p>This allows us to extend the above example with these features:</p> <ul> <li>Custom error message displayed after the user interacted with a control (i.e. when <code>$touched</code> is set)</li> <li>Custom error message displayed upon submitting the form (<code>$submitted</code> is set), even if the user didn't interact with a control</li> </ul> <p> <div> <a ng-click="openPlunkr('examples/example-example33')" class="btn pull-right"> <i class="glyphicon glyphicon-edit"> </i> Edit in Plunker</a> <div class="runnable-example" path="examples/example-example33" module="formExample"> <div class="runnable-example-file" name="index.html" language="html" type="html"> <pre><code><div ng-controller="ExampleController"> <form name="form" class="css-form" novalidate> Name: <input type="text" ng-model="user.name" name="uName" required="" /> <br /> <div ng-show="form.$submitted || form.uName.$touched"> <div ng-show="form.uName.$error.required">Tell us your name.</div> </div> E-mail: <input type="email" ng-model="user.email" name="uEmail" required="" /> <br /> <div ng-show="form.$submitted || form.uEmail.$touched"> <span ng-show="form.uEmail.$error.required">Tell us your email.</span> <span ng-show="form.uEmail.$error.email">This is not a valid email.</span> </div> Gender: <input type="radio" ng-model="user.gender" value="male" />male <input type="radio" ng-model="user.gender" value="female" />female <br /> <input type="checkbox" ng-model="user.agree" name="userAgree" required="" /> I agree: <input ng-show="user.agree" type="text" ng-model="user.agreeSign" required="" /> <br /> <div ng-show="form.$submitted || form.userAgree.$touched"> <div ng-show="!user.agree || !user.agreeSign">Please agree and sign.</div> </div> <input type="button" ng-click="reset(form)" value="Reset" /> <input type="submit" ng-click="update(user)" value="Save" /> </form> </div></code></pre> </div> <div class="runnable-example-file" name="script.js" language="js" type="js"> <pre><code>angular.module('formExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.master = {}; $scope.update = function(user) { $scope.master = angular.copy(user); }; $scope.reset = function(form) { if (form) { form.$setPristine(); form.$setUntouched(); } $scope.user = angular.copy($scope.master); }; $scope.reset(); }]);</code></pre> </div> <iframe class="runnable-example-frame" src="examples/example-example33/index.html" name="example-example33"></iframe> </div> </div> </p> <h1 id="custom-model-update-triggers">Custom model update triggers</h1> <p>By default, any change to the content will trigger a model update and form validation. You can override this behavior using the <a href="api/ng/directive/ngModelOptions">ngModelOptions</a> directive to bind only to specified list of events. I.e. <code>ng-model-options="{ updateOn: 'blur' }"</code> will update and validate only after the control loses focus. You can set several events using a space delimited list. I.e. <code>ng-model-options="{ updateOn: 'mousedown blur' }"</code></p> <p><img alt="animation showing debounced input" src="img/guide/forms-update-on-blur.gif"></p> <p>If you want to keep the default behavior and just add new events that may trigger the model update and validation, add "default" as one of the specified events.</p> <p>I.e. <code>ng-model-options="{ updateOn: 'default blur' }"</code></p> <p>The following example shows how to override immediate updates. Changes on the inputs within the form will update the model only when the control loses focus (blur event).</p> <p> <div> <a ng-click="openPlunkr('examples/example-example34')" class="btn pull-right"> <i class="glyphicon glyphicon-edit"> </i> Edit in Plunker</a> <div class="runnable-example" path="examples/example-example34" module="customTriggerExample"> <div class="runnable-example-file" name="index.html" language="html" type="html"> <pre><code><div ng-controller="ExampleController"> <form> Name: <input type="text" ng-model="user.name" ng-model-options="{ updateOn: 'blur' }" /><br /> Other data: <input type="text" ng-model="user.data" /><br /> </form> <pre>username = "{{user.name}}"</pre> <pre>userdata = "{{user.data}}"</pre> </div></code></pre> </div> <div class="runnable-example-file" name="script.js" language="js" type="js"> <pre><code>angular.module('customTriggerExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.user = {}; }]);</code></pre> </div> <iframe class="runnable-example-frame" src="examples/example-example34/index.html" name="example-example34"></iframe> </div> </div> </p> <h1 id="non-immediate-debounced-model-updates">Non-immediate (debounced) model updates</h1> <p>You can delay the model update/validation by using the <code>debounce</code> key with the <a href="api/ng/directive/ngModelOptions">ngModelOptions</a> directive. This delay will also apply to parsers, validators and model flags like <code>$dirty</code> or <code>$pristine</code>.</p> <p><img alt="animation showing debounced input" src="img/guide/forms-debounce.gif"></p> <p>I.e. <code>ng-model-options="{ debounce: 500 }"</code> will wait for half a second since the last content change before triggering the model update and form validation.</p> <p>If custom triggers are used, custom debouncing timeouts can be set for each event using an object in <code>debounce</code>. This can be useful to force immediate updates on some specific circumstances (like blur events).</p> <p>I.e. <code>ng-model-options="{ updateOn: 'default blur', debounce: { default: 500, blur: 0 } }"</code></p> <p>If those attributes are added to an element, they will be applied to all the child elements and controls that inherit from it unless they are overridden.</p> <p>This example shows how to debounce model changes. Model will be updated only 250 milliseconds after last change.</p> <p> <div> <a ng-click="openPlunkr('examples/example-example35')" class="btn pull-right"> <i class="glyphicon glyphicon-edit"> </i> Edit in Plunker</a> <div class="runnable-example" path="examples/example-example35" module="debounceExample"> <div class="runnable-example-file" name="index.html" language="html" type="html"> <pre><code><div ng-controller="ExampleController"> <form> Name: <input type="text" ng-model="user.name" ng-model-options="{ debounce: 250 }" /><br /> </form> <pre>username = "{{user.name}}"</pre> </div></code></pre> </div> <div class="runnable-example-file" name="script.js" language="js" type="js"> <pre><code>angular.module('debounceExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.user = {}; }]);</code></pre> </div> <iframe class="runnable-example-frame" src="examples/example-example35/index.html" name="example-example35"></iframe> </div> </div> </p> <h1 id="custom-validation">Custom Validation</h1> <p>Angular provides basic implementation for most common HTML5 <a href="api/ng/directive/input">input</a> types: (<a href="api/ng/input/input[text]">text</a>, <a href="api/ng/input/input[number]">number</a>, <a href="api/ng/input/input[url]">url</a>, <a href="api/ng/input/input[email]">email</a>, <a href="api/ng/input/input[date]">date</a>, <a href="api/ng/input/input[radio]">radio</a>, <a href="api/ng/input/input[checkbox]">checkbox</a>), as well as some directives for validation (<code>required</code>, <code>pattern</code>, <code>minlength</code>, <code>maxlength</code>, <code>min</code>, <code>max</code>).</p> <p>With a custom directive, you can add your own validation functions to the <code>$validators</code> object on the <a href="api/ng/type/ngModel.NgModelController"><code>ngModelController</code></a>. To get a hold of the controller, you require it in the directive as shown in the example below.</p> <p>Each function in the <code>$validators</code> object receives the <code>modelValue</code> and the <code>viewValue</code> as parameters. Angular will then call <code>$setValidity</code> internally with the function's return value (<code>true</code>: valid, <code>false</code>: invalid). The validation functions are executed every time an input is changed (<code>$setViewValue</code> is called) or whenever the bound <code>model</code> changes. Validation happens after successfully running <code>$parsers</code> and <code>$formatters</code>, respectively. Failed validators are stored by key in <a href="api/ng/type/ngModel.NgModelController#$error"><code>ngModelController.$error</code></a>.</p> <p>Additionally, there is the <code>$asyncValidators</code> object which handles asynchronous validation, such as making an <code>$http</code> request to the backend. Functions added to the object must return a promise that must be <code>resolved</code> when valid or <code>rejected</code> when invalid. In-progress async validations are stored by key in <a href="api/ng/type/ngModel.NgModelController#$pending"><code>ngModelController.$pending</code></a>.</p> <p>In the following example we create two directives:</p> <ul> <li><p>An <code>integer</code> directive that validates whether the input is a valid integer. For example, <code>1.23</code> is an invalid value, since it contains a fraction. Note that we validate the viewValue (the string value of the control), and not the modelValue. This is because input[number] converts the viewValue to a number when running the <code>$parsers</code>.</p> </li> <li><p>A <code>username</code> directive that asynchronously checks if a user-entered value is already taken. We mock the server request with a <code>$q</code> deferred.</p> </li> </ul> <p> <div> <a ng-click="openPlunkr('examples/example-example36')" class="btn pull-right"> <i class="glyphicon glyphicon-edit"> </i> Edit in Plunker</a> <div class="runnable-example" path="examples/example-example36" module="form-example1"> <div class="runnable-example-file" name="index.html" language="html" type="html"> <pre><code><form name="form" class="css-form" novalidate> <div> Size (integer 0 - 10): <input type="number" ng-model="size" name="size" min="0" max="10" integer />{{size}}<br /> <span ng-show="form.size.$error.integer">The value is not a valid integer!</span> <span ng-show="form.size.$error.min || form.size.$error.max"> The value must be in range 0 to 10!</span> </div> <div> Username: <input type="text" ng-model="name" name="name" username />{{name}}<br /> <span ng-show="form.name.$pending.username">Checking if this name is available...</span> <span ng-show="form.name.$error.username">This username is already taken!</span> </div> </form></code></pre> </div> <div class="runnable-example-file" name="script.js" language="js" type="js"> <pre><code>var app = angular.module('form-example1', []); var INTEGER_REGEXP = /^\-?\d+$/; app.directive('integer', function() { return { require: 'ngModel', link: function(scope, elm, attrs, ctrl) { ctrl.$validators.integer = function(modelValue, viewValue) { if (ctrl.$isEmpty(modelValue)) { // consider empty models to be valid return true; } if (INTEGER_REGEXP.test(viewValue)) { // it is valid return true; } // it is invalid return false; }; } }; }); app.directive('username', function($q, $timeout) { return { require: 'ngModel', link: function(scope, elm, attrs, ctrl) { var usernames = ['Jim', 'John', 'Jill', 'Jackie']; ctrl.$asyncValidators.username = function(modelValue, viewValue) { if (ctrl.$isEmpty(modelValue)) { // consider empty model valid return $q.when(); } var def = $q.defer(); $timeout(function() { // Mock a delayed response if (usernames.indexOf(modelValue) === -1) { // The username is available def.resolve(); } else { def.reject(); } }, 2000); return def.promise; }; } }; });</code></pre> </div> <iframe class="runnable-example-frame" src="examples/example-example36/index.html" name="example-example36"></iframe> </div> </div> </p> <h1 id="modifying-built-in-validators">Modifying built-in validators</h1> <p>Since Angular itself uses <code>$validators</code>, you can easily replace or remove built-in validators, should you find it necessary. The following example shows you how to overwrite the email validator in <code>input[email]</code> from a custom directive so that it requires a specific top-level domain, <code>example.com</code> to be present. Note that you can alternatively use <code>ng-pattern</code> to further restrict the validation.</p> <p> <div> <a ng-click="openPlunkr('examples/example-example37')" class="btn pull-right"> <i class="glyphicon glyphicon-edit"> </i> Edit in Plunker</a> <div class="runnable-example" path="examples/example-example37" module="form-example-modify-validators"> <div class="runnable-example-file" name="index.html" language="html" type="html"> <pre><code><form name="form" class="css-form" novalidate> <div> Overwritten Email: <input type="email" ng-model="myEmail" overwrite-email name="overwrittenEmail" /> <span ng-show="form.overwrittenEmail.$error.email">This email format is invalid!</span><br> Model: {{myEmail}} </div> </form></code></pre> </div> <div class="runnable-example-file" name="script.js" language="js" type="js"> <pre><code>var app = angular.module('form-example-modify-validators', []); app.directive('overwriteEmail', function() { var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@example\.com$/i; return { require: 'ngModel', restrict: '', link: function(scope, elm, attrs, ctrl) { // only apply the validator if ngModel is present and Angular has added the email validator if (ctrl && ctrl.$validators.email) { // this will overwrite the default Angular email validator ctrl.$validators.email = function(modelValue) { return ctrl.$isEmpty(modelValue) || EMAIL_REGEXP.test(modelValue); }; } } }; });</code></pre> </div> <iframe class="runnable-example-frame" src="examples/example-example37/index.html" name="example-example37"></iframe> </div> </div> </p> <h1 id="implementing-custom-form-controls-using-ngmodel-">Implementing custom form controls (using <code>ngModel</code>)</h1> <p>Angular implements all of the basic HTML form controls (<a href="api/ng/directive/input">input</a>, <a href="api/ng/directive/select">select</a>, <a href="api/ng/directive/textarea">textarea</a>), which should be sufficient for most cases. However, if you need more flexibility, you can write your own form control as a directive.</p> <p>In order for custom control to work with <code>ngModel</code> and to achieve two-way data-binding it needs to:</p> <ul> <li>implement <code>$render</code> method, which is responsible for rendering the data after it passed the <a href="api/ng/type/ngModel.NgModelController#$formatters"><code>NgModelController.$formatters</code></a>,</li> <li>call <code>$setViewValue</code> method, whenever the user interacts with the control and model needs to be updated. This is usually done inside a DOM Event listener.</li> </ul> <p>See <a href="guide/directive"><code>$compileProvider.directive</code></a> for more info.</p> <p>The following example shows how to add two-way data-binding to contentEditable elements.</p> <p> <div> <a ng-click="openPlunkr('examples/example-example38')" class="btn pull-right"> <i class="glyphicon glyphicon-edit"> </i> Edit in Plunker</a> <div class="runnable-example" path="examples/example-example38" module="form-example2"> <div class="runnable-example-file" name="index.html" language="html" type="html"> <pre><code><div contentEditable="true" ng-model="content" title="Click to edit">Some</div> <pre>model = {{content}}</pre> <style type="text/css"> div[contentEditable] { cursor: pointer; background-color: #D0D0D0; } </style></code></pre> </div> <div class="runnable-example-file" name="script.js" language="js" type="js"> <pre><code>angular.module('form-example2', []).directive('contenteditable', function() { return { require: 'ngModel', link: function(scope, elm, attrs, ctrl) { // view -> model elm.on('blur', function() { scope.$apply(function() { ctrl.$setViewValue(elm.html()); }); }); // model -> view ctrl.$render = function() { elm.html(ctrl.$viewValue); }; // load init value from DOM ctrl.$setViewValue(elm.html()); } }; });</code></pre> </div> <iframe class="runnable-example-frame" src="examples/example-example38/index.html" name="example-example38"></iframe> </div> </div> </p>