We have been using checkbox in Angular js which returns either true or false depending on if it's checked or unchecked.
Checked = true
Unchecked = false
Now, if a condition comes that we want not true/false but some other value on checkbox checked or unchecked than we can use ng-true-value and ng-false-value for this.
As per my requirement I have a checkbox that returns "Employee" if checked and returns "Users" if unchecked.
In order to do that, let's declare a controller and set the initial value of the checkbox as below:
- var myApp = angular.module("myModule", []);
-
- myApp.controller("myController", function ($scope) {
-
- $scope.chk = "Employee";
- });
In the above code, we have declared an app and a controller and have set the scope variable chk value as Employee.
Now create an html as per below code:
- <div ng-app="myModule">
- <div ng-controller="myController">
- Employee?
- <input type="checkbox" ng-model="chk" ng-true-value="'Employee'" ng-false-value="'User'" />
- <div> This is a :
- {{chk}}
- </div>
- </div>
-
- </div>
We have assigned ng-model as chk, which was initialized in the controller defined earlier.
Also, we have assigned ng-true-value as 'Employee' and ng-false-value as 'User'.
This is to make sure that when the checkbox is true(i.e. checked) its return value is Employee and when the checkbox is false (i.e. unchecked) its return value is User.
The output of the code is as below:
On Page Load:
On Unchecking the checkbox:
On checking the checkbox again: