Hint : respect the "dot rule".
<input ng-model="data.defaultAssigneeCheckbox" type="checkbox" />
Pergunta
I have a checkbox:
<input ng-model="defaultAssigneeCheckbox" type="checkbox"/>
<p>{{defaultAssigneeCheckbox}}</p>
<button type="submit">Save</button>
Paragraph below it shows and updates its state properly between false
and true
.
Clicking button runs controller function:
$scope.updateProject = function () {
var project = $scope.project;
console.log(typeof $scope.defaultAssigneeCheckbox)
console.log($scope.defaultAssigneeCheckbox)
if (!$scope.defaultAssigneeCheckbox) {
delete project.defaultAssignee;
}
};
When I click button it shows the checkbox as true regardless of whether the checkbox is checked or not.
What am I doing wrong?
Solução
Hint : respect the "dot rule".
<input ng-model="data.defaultAssigneeCheckbox" type="checkbox" />
Outras dicas
Had the same problem yesterday, try using ng-true-value & ng-false-value
<input type="checkbox" ng-model="model.value" ng-true-value="1" ng-false-value="0">
In your case use true & false
What is the output of console.log(typeof $scope.defaultAssigneeCheckbox)? I have a feeling it's 'string' in which case $scope.defaultAssigneeCheckbox is always true. therefore try this:
if ($scope.defaultAssigneeCheckbox != true) {
delete project.defaultAssignee;
}
if that works figure out if you are ok with that or if you need to force a boolean. In which case @Mario Campa's solution looks good. Personally, I'd prefer a boolean because experience dictates that it will be more useful in these cases.