2

I have checked question How to bind to list of checkbox values with AngularJS. But this question explains list of arrays and best ways to handle it in Angular controller.

<input type='checkbox' name="filter" checked>

How can we bind value to checkbox to have value as modal 0 when unchecked and 1 when checked? What should be in HTML and Controller?

$scope.filter = 0;
Community
  • 1
  • 1
Somnath Muluk
  • 55,015
  • 38
  • 216
  • 226

3 Answers3

4

Try this:

$scope.filter = 0;//or 1

HTML:

<input type="checkbox" ng-model="filter" ng-true-value="1" ng-false-value="0">
Slava Utesinov
  • 13,410
  • 2
  • 19
  • 26
0

Here is an modified example based on the AngularJS documentation

Controller

angular.module('checkboxExample', [])
.controller('ExampleController', ['$scope', function($scope) {
    $scope.checkboxModel = 0; //Set checkbox to unchecked
}]);

HTML

<input type="checkbox" ng-model="checkboxModel" ng-true-value="1" ng-false-value="0">
Weedoze
  • 13,683
  • 1
  • 33
  • 63
0

Angular has provided ng-true-value & ng-false-value directives to fullfill your requirement. Through it you can associate true/false values with checkbox and same will be using by model as well.

You can try below code

<div ng-controller="ValidateCtrl">
    Check Value: <input type="checkbox" ng-true-value="1" ng-false-value="0" ng-model="checkBoxModel"/>
</div>

Controller
---------
function ValidateCtrl($scope) {
   $scope.checkBoxModel = '1';
};

So initially checkbox will be checked.

Suneet Bansal
  • 2,664
  • 1
  • 14
  • 18