0

无法解决涉及从 API 生成的 Angular 复选框表单的问题。

我可以创建一个复选框,但有两个问题:复选框的选中状态与来自 API 的值不匹配,当我单击复选框时,名称值从其默认值更改为“true”或“false”。已经看到其他类似的问题,但无法使其正常工作。戳这里和下面的源代码:

<!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>
4

2 回答 2

3

简单地说,布尔值应该是truefalse只是而不是字符串'true''false'

此外,不需要ng-checked指令。您还需要{{index}}在表单字段中使用,以便它成为表单的独特元素,例如serviceSelect-{{$index}}

标记

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

演示 Plunkr

于 2015-07-01T21:36:06.427 回答
0

Angular 的复选框是真还是假。代码应该是这样的:

<input type="checkbox" name="serviceSelect" ng-model="fruit.selected" ng-value="{{fruit.name}}" ng-checked="fruit.selected">
于 2015-07-01T21:37:39.053 回答