Should we use the <form> element when working with AngularJS , since two-way data binding offers us direct control over form data in our controllers?
Should we use forms to respect the HTML structure, or are there other reasons why we should continue to use them? What are the disadvantages of an approach without using <form> elements?
angular.module('formsOrNot', []) .controller('ExampleController', ['$scope', function($scope) {
input.ng-invalid-required.ng-dirty, input.ng-invalid-email.ng-dirty { border: 1px solid red; } input.ng-invalid-required.ng-pristine, input.ng-invalid-email.ng-pristine { border: 1px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="formsOrNot"> <div ng-controller="ExampleController"> <header> <h1>Forms or not</h1> </header> <section> <h2>Form example</h2> <form ng-submit="submit1()" novalidate> Enter text and hit enter: <input type="email" ng-model="text1" name="text1" required/> <input type="submit" id="submit1" value="Submit" /> <pre>list1={{list1}}</pre> </form> </section> <section> <h2>Without form</h2> Enter text and hit enter: <input type="email" ng-model="text2" name="text2" required/> <input type="submit" id="submit2" value="Submit" ng-click="submit2()"/> <pre>list2={{list2}}</pre> </section> </div> </div>
Update as proof of @ZenDD's incorrect initial answer:
The two-way data binding works fine without form element, but without it you wont' be able to use benefits of Angular built-in form validation - incorrect
Try updating the fragment, this proves that the input is checked, not the form. Validation classes are added to both sections with or without a form.
In addition, the unvalidate effect unvalidate same for both sections, since a section without a form does not need this attribute.
So validation doesn't matter, right?
Update after @ZenDD updated his answer
We must use form elements because Angular treats them as directives that Angular uses to instantiate FormController . This controller allows us to use validation properties on elements that allow us to validate fields contained in the form. These properties appear in the @ZenDD update of the native response: $error, $pristine, $dirty
source share