Home > Article > Web Front-end > Simple way to handle radio buttons and checkboxes using AngularJS_AngularJS
AngularJS’s form processing is quite simple. When AngularJS uses two-way data binding for form validation, it is essentially helping us with form processing.
There are many examples of using checkboxes, and there are many ways we can deal with them. In this article we will take a look at binding checkboxes and radio buttons to data variables and what we can do with it.
Create Angular form
In this article, we need two files: index.html and app.js. app.js is where all the Angular code is held (it's not big), and index.html is where the actions run. First we create the AngularJS file.
// app.js var formApp = angular.module('formApp', []) .controller('formController', function($scope) { // we will store our form data in this object $scope.formData = {}; });
In this file, all we do is create the Angular application. We also created a controller and an object to hold all the form data.
Let’s take a look at the index.html file. In this file, we create the form and then perform data binding. We used Bootstrap to quickly layout the page.
<-- index.html --> <!DOCTYPE html> <html> <head> <!-- CSS --> <!-- load up bootstrap and add some spacing --> <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"> <style> body { padding-top:50px; } form { margin-bottom:50px; } </style> <!-- JS --> <!-- load up angular and our custom script --> <script src="http://code.angularjs.org/1.2.13/angular.js"></script> <script src="app.js"></script> </head> <!-- apply our angular app and controller --> <body ng-app="formApp" ng-controller="formController"> <div class="col-xs-12 col-sm-10 col-sm-offset-1"> <h2>Angular Checkboxes and Radio Buttons</h2> <form> <!-- NAME INPUT --> <div class="form-group"> <label>Name</label> <input type="text" class="form-control" name="name" ng-model="formData.name"> </div> <!-- =============================================== --> <!-- ALL OUR CHECKBOXES AND RADIO BOXES WILL GO HERE --> <!-- =============================================== --> <!-- SUBMIT BUTTON (DOESNT DO ANYTHING) --> <button type="submit" class="btn btn-danger btn-lg">Send Away!</button> </form> <!-- SHOW OFF OUR FORMDATA OBJECT --> <h2>Sample Form Object</h2> <pre class="brush:php;toolbar:false"> {{ formData }}