Search code examples
javascriptangularjscheckboxangularjs-controllerangularjs-forms

Angular Checkboxes not Binding Properly


Having trouble figuring out this problem involving an Angular checkbox form generated from an API.

I can create a checkboxes but two problems: The checkedness of the boxes does not match the values in what's coming from the API, and when I click the checkboxes the name value changes from its default to "true" or "false." Have seen other similar questions but can't get this to work. Plunk here and source code below:

<!doctype html>
<html ng-app="checkTest">
    <head>
        <meta charset="utf-8">
        <title>Angular Multiple Checkboxes</title>
        <style>
            label {display:block;}
        </style>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.js"></script>
        <script type="text/javaScript">
        var jsonObj = {"fruits":[
            {
              "name": "Apple",
              "desc": "abcdefg",
              "selected": "true",
              "status": "Created"
            },
            {
              "name": "Broccoli",
              "desc": "abcdefg",
              "selected": "true",
              "status": "None"
            },
            {
              "name": "Cucumber",
              "desc": "abcdefg",
              "selected": "false",
              "status": "Created"
            },
            {
              "name": "Daikon",
              "desc": "abcdefg",
              "selected": "false",
              "status": "None"
            }
      ]};
            var fruitsObj = jsonObj.fruits;
        </script>

    </head>

    <body>
        <div ng-controller="MainCtrl">

            <label ng-repeat="fruit in fruits">
                <input type="checkbox" name="fruitSelect" ng-model="fruit.name" ng-value="{{fruit.name}}" ng-checked="fruit.selected"> {{fruit.name}}
            </label>
            <p>Services: {{fruits}}</p>
        </div>

        <script type="text/javaScript">

            var app = angular.module('checkTest', []);

            app.controller('MainCtrl', function($scope) {
                $scope.fruits = fruitsObj;
            });

        </script>
    </body>
</html>

Solution

  • Simply the booleans should be true or false only rather than string 'true' or 'false'

    Additionally there is not need of ng-checked directive. You also need to use {{index}} in form field so that it will become an unique element of form like by doing serviceSelect-{{$index}}

    Markup

    <input 
        type="checkbox" 
        name="serviceSelect-{{$index}}" 
        ng-model="fruit.selected" 
        ng-value="{{fruit.name}}" /> 
    

    Demo Plunkr