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;
1

3 Answers 3

4

Try this:

$scope.filter = 0;//or 1

HTML:

<input type="checkbox" ng-model="filter" ng-true-value="1" ng-false-value="0">
Sign up to request clarification or add additional context in comments.

Comments

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">

2 Comments

Good copy of my answer.
Sorry I did not saw it... I was writing my answer
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.