0

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'/>
    </div>
</form>

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!

2 Answers 2

2

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

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

and

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

Sign up to request clarification or add additional context in comments.

1 Comment

great, glad to help u :)
0

Just in addition to this. I"ve noticed that use a boolean on the checkbox can cause issues.

Convert your model into a string (or int) and change the input to be something like this will work

<input type='checkbox' ng-model='mgModel' ng-true-value="'true'" ng-false-value="'false'" />

But if you true to use a straight boolean. You'll find it'll not send the change up to parent controllers etc. So this will fail or cause wired binding issues

<input type='checkbox' ng-model='mgModel' ng-true-value="true" ng-false-value="false" />

So if you're having issues with bind a true/false value. Try changing it to a string or int.

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.