Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS checkbox model value is undefined

I have a problem where I'm attempting to post the value of a checkbox in my model to the server and as the checkbox has not been interacted with on the form, angular seems to have not assigned it a value, when I ask for the value of the checkbox it comes back as undefined.

Here is my markup:

<div class="form-group">
    <input id="templateDisable" type="checkbox" ng-model="template.disabled" />
    <label for="templateDisable">Disabled</label>
</div>

And here's a reduced version of my save action on my controller:

$scope.save = function (form) {
    if (form.$valid) {
        var formData = new FormData();
        // this is the problem line of code
        formData.append("disabled", $scope.template.disabled);
        // ... some other stuff
    }
};

Actually, ticking then unticking the checkbox before I hit the save action results in the template.disabled property being false, which is what I would have expected without any manual intervention.

I've seen other related questions, e.g. AngularJS: Initial checkbox value not in model but surely stuff like a simple checkbox should be baked in? I shouldn't have to be writing directives to manage checkboxes surely?

like image 484
A. Murray Avatar asked Dec 23 '13 11:12

A. Murray


2 Answers

This is per design. If you want a default value on your model than you should initialise it inside the controller (recommended), or make use of ng-init.

app.controller('AppController',
    [
      '$scope',
      function($scope) {
        $scope.template = {
          disabled = false
        };
      }
    ]
  );
<div class="form-group">
  <input type="checkbox" ng-model="template.disabled" ng-init="template.disabled=false" />
  <label>Disabled</label>
</div>
like image 137
Stewie Avatar answered Nov 12 '22 01:11

Stewie


The following will always set the state back to "unchecked" when the page is loaded (or refreshed). In other words it will overwrite the user's actual selection whenever the page is refreshed.

<input type="checkbox" ng-model="template.disabled" 
 ng-init="template.disabled=false" />

If, however, you want the checkbox state set to a default state initially and you also want it to remember user interactions, then the following is what you want.

<input type="checkbox" ng-model="template.disabled" 
 ng-init="template.disabled = template.disabled || false" />
like image 41
Neil Atkinson Avatar answered Nov 12 '22 02:11

Neil Atkinson