Reputation: 2084
I have a form and before I submit this form I want to do something based on a checkbox if its selected or not.
this is my checkbox :
<input type="checkbox" name="resident" id="resident"
ng-model="resident" ng-init="resident=false">
in my controller I have this :
$scope.submitForm = function (isValid) {
if(!$scope.resident){
//code...
}else{
//code...
}
}
but then I always get the value of this checkbox as undefined even though I have initialized it to false
.
I don't want to work with ng-change
since I only need to know the value for the checkbox and not to do treatments whenever it changed.
how can I solve this ?
Upvotes: 2
Views: 42
Reputation: 6766
The code you have attached to the question does not contain any issue. The issue is some where else in the code that you have not posted here. Refer below code it does work.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="">
<input type="checkbox" name="resident" id="resident"
ng-model="resident" ng-init="resident=false">{{resident}}
</div>
Possible issue: Refer to the Scope that is attached to the input checkbox sometimes happens that variable or model has been in parent scope and we are trying to manipulate in child scope. Use chrome tool like batrang that can guide you better with respect to the child and parent scope inspection.
Upvotes: 2
Reputation: 3515
View:
<input type="checkbox" name="resident" id="resident" ng-model="resident.checked">
Controller:
$scope.resident = {
checked: false;
}
That's it! The model will automatically switch from false
to true
via the ng-model
directive.
See http://jsfiddle.net/Lvc0u55v/2989/
Upvotes: 1