diff --git a/src/ng/directive/form.js b/src/ng/directive/form.js index 0cd70844ee72..cf02ac5cb6ac 100644 --- a/src/ng/directive/form.js +++ b/src/ng/directive/form.js @@ -1,13 +1,18 @@ 'use strict'; -/* global -nullFormCtrl */ +/* global + -nullFormCtrl, + -ATTEMPTED_CLASS +*/ var nullFormCtrl = { $addControl: noop, $removeControl: noop, $setValidity: noop, $setDirty: noop, - $setPristine: noop -}; + $setPristine: noop, + $setAttempted: noop +}, +ATTEMPTED_CLASS = 'ng-attempted'; /** * @ngdoc object @@ -60,6 +65,7 @@ function FormController(element, attrs) { form.$pristine = true; form.$valid = true; form.$invalid = false; + form.$attempted = false; parentForm.$addControl(form); @@ -206,9 +212,22 @@ function FormController(element, attrs) { control.$setPristine(); }); }; + + /** + * @ngdoc function + * @name ng.directive:form.FormController#$setAttempted + * @methodOf ng.directive:form.FormController + * + * @description + * Sets the form to its submission attempted state. + */ + form.$setAttempted = function (value) { + value ? element.addClass(ATTEMPTED_CLASS) : element.removeClass(ATTEMPTED_CLASS); + form.$attempted = value; + parentForm.$setAttempted(value); + }; } - /** * @ngdoc directive * @name ng.directive:ngForm @@ -253,6 +272,7 @@ function FormController(element, attrs) { * - `ng-invalid` Is set if the form is invalid. * - `ng-pristine` Is set if the form is pristine. * - `ng-dirty` Is set if the form is dirty. + * - `ng-attempted` Is set if the form was submitted in invalid state. * * * # Submitting a form and preventing the default action @@ -350,6 +370,12 @@ var formDirectiveFactory = function(isNgForm) { removeEventListenerFn(formElement[0], 'submit', preventDefaultListener); }, 0, false); }); + + formElement.on('submit', function() { + scope.$apply(function() { + controller.$setAttempted(controller.$invalid); + }); + }); } var parentFormCtrl = formElement.parent().controller('form'), diff --git a/test/ng/directive/formSpec.js b/test/ng/directive/formSpec.js index dde6f0a026c8..fd94aa5e5a19 100644 --- a/test/ng/directive/formSpec.js +++ b/test/ng/directive/formSpec.js @@ -316,6 +316,9 @@ describe('form', function() { child.$setDirty(); expect(parent.$dirty).toBeTruthy(); + + child.$setAttempted(true); + expect(parent.$attempted).toBeTruthy(); }); @@ -593,4 +596,25 @@ describe('form', function() { expect(nestedInputCtrl.$dirty).toBe(false); }); }); + + describe('$setAttempted', function() { + beforeEach(function() { + doc = $compile( + '
')(scope); + + scope.$digest(); + }); + + it('should not init in attempted state', function() { + expect(scope.form.$attempted).toBe(false); + }); + + it('should be in attempted state when invalid and submitted', function() { + browserTrigger(doc, 'submit'); + expect(scope.form.$attempted).toBe(true); + }); + }); });