Shih-Min Lee Shih-Min Lee - 1 year ago 73
AngularJS Question

Angular checkbox not submitted

I have an angular form with a checkbox ready to submit.

<form name="productForm" class="form-horizontal" role="form" ng-submit='action(productForm.$valid)' novalidate>
<div class="form-group">
<input type='checkbox' name='subtract' data-ng-model='product.subtract'/>

The problem is The default value of this thing in database is 1.

I assume if I don't select the checkbox it will record 0 in the database for me. But somehow this input checkbox is not submitted and the db just takes the defined default value '1'.

Any chance someone know what is happening here? Thanks!

Answer Source

seems like you dont initialize the scope variable product.subtract in the controller as,

$scope.product = {};
$scope.product.subtract = 0; //not selected by default


<input type='checkbox' name='subtract' data-ng-model='product.subtract' ng-true-value="1" ng-false-value="0" />

ng-true-value & ng-false-value represent the checkbox true false statuses based on checked.

if you do not initialize a scope variable within the controller or using ng-init then there is no scope variable create until you made a change to the ng-model. so here, if u dont have the scope variable, and then you submit the form without ticking the checkbox then there is no scope variable called $scope.product.subtract.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download