Rectangle 27 0

javascript How do I get checkboxes to bind to boolean values in my data model?


function ShoppingListCtrl($scope) {
    $scope.shoppingList = [
      {
      "text": "V8 fusion",
      "isGotten": true
      }, 
      {
      "text": "Whole milk container",
      "isGotten": false
      },
      {
      "text": "Protein bars",
      "isGotten": true
      }
   ];
};

If you just remove the quotes as follows, your code then works correctly. A working example is at http://plnkr.co/edit/gkchmOBTkBtVv3TijlZW .

The problem is that you have "true" and "false" in quotes, which makes them strings instead of booleans that Angular can bind the checkbox to.

Note
Rectangle 27 0

javascript How do I get checkboxes to bind to boolean values in my data model?


<p ng-repeat="item in list1" class="item" id="{{item.id}}">
  <strong>{{item.id}}</strong> <input name='obj1_data' type="checkbox" ng-model="list1[$index].data" ng-true-value="1" ng-false-value="0"> Click this to change data value below
</p>
<pre>{{list1 | json}}</pre>

Depending on your data you may not want pure true/false in your code. AngularJS evaluates true/false and 1/0 booleans into strings anyway, so you may be better off using strings.

In this codepen I use "1" and "0" for boolean values, and ngTrueValue and ngFalseValue to tell AngularJS how to keep the bindings intact. Very simple and clean.

Note