Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

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;
share|improve this question
up vote 2 down vote accepted

Try this:

$scope.filter = 0;//or 1

HTML:

<input type="checkbox" ng-model="filter" ng-true-value="1" ng-false-value="0">
share|improve this answer
1  
jsfiddle.net/5c617scr – Lucas Bader Aug 9 at 6:35

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">
share|improve this answer
1  
Good copy of my answer. – Slava Utesinov Aug 9 at 6:38
    
Sorry I did not saw it... I was writing my answer – Weedoze Aug 9 at 6:39

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.