无法解决涉及从API生成的Angular复选框表单的问题。
我可以创建一个复选框,但有两个问题:框的选中性与来自API的内容中的值不匹配,当我单击复选框时,名称值从默认值更改为“true”或“false”。 “已经看过其他类似的问题,但无法让这个工作。 Plunk here以及以下源代码:
<!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>
答案 0 :(得分:3)
只需将布尔值设为true
或false
而不是字符串'true'
或'false'
此外,不需要ng-checked
指令。您还需要在表单字段中使用{{index}}
,以便它成为表单的唯一元素,就像执行serviceSelect-{{$index}}
<强>标记强>
<input
type="checkbox"
name="serviceSelect-{{$index}}"
ng-model="fruit.selected"
ng-value="{{fruit.name}}" />
答案 1 :(得分:0)
Angular的Checkbox是true还是false。代码应为:
<input type="checkbox" name="serviceSelect" ng-model="fruit.selected" ng-value="{{fruit.name}}" ng-checked="fruit.selected">