AngularJS > Forms & Validations

Check box in AngularJS

How to work with Checkbox in AngularJS?


In previous post, we learnt how to work with text boxes with AngularJS. In this post, we shall learn how to get the checkbox checked status as well as how to set the custom value to the check box.

In below code snippet, <script> block has a controller defined with chkVal1 and chkVal2 properties and its default values are set. We have also defined a function GetValue that alert current value of both properties based on whether check boxes are checked or not.

<h2>Check box</h2>
<script>
    var app = angular.module("app", []);
    app.controller("CheckBoxController", function ($scope) {
        $scope.chkVal1 = false;
        $scope.chkVal2 = 'Female';

        $scope.GetValue = function () {
            alert($scope.chkVal1 + ' ' + $scope.chkVal2);
        }
    });
</script>

<div ng-app="app" ng-controller="CheckBoxController">
    Simple: <input id="chk1" type="checkbox" ng-model="chkVal1" /> {{ chkVal1 }}
    <p>
        Checkbox with custom value:
        Are you male? <input id="chk2" type="checkbox" ng-model="chkVal2"
ng-false-value="'Female'" ng-true-value="'Male'" />
        {{ chkVal2 }}
    </p>
    <button ng-click="GetValue()">Get Value</button>
</div>

In the HTML block, the first check box simply set the ng-model directive to the 1st property defined.

The 2nd checkbox, ng-model directive is set to 2nd property. Apart from settting ng-model directive in the 2nd checkbox, we have also set the ng-false-value and ng-true-value directive that set its model value based on whether it is checked or not.

Clicking on button, calls GetValue function that shows the current value of checkboxes.

Output

Checkbox in AngularJs

 Views: 23688 | Post Order: 49




Write for us






Hosting Recommendations