gpt4 book ai didi

javascript - Angular 复选框未正确绑定(bind)

转载 作者:行者123 更新时间:2023-11-28 19:08:38 27 4
gpt4 key购买 nike

无法解决涉及从 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>

最佳答案

简单来说, bool 值应该是 truefalse 而不是字符串 'true''false'

此外,不需要 ng-checked 指令。您还需要在表单字段中使用 {{index}} ,以便它将成为表单的唯一元素,就像执行 serviceSelect-{{$index}}

标记

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

Demo Plunkr

关于javascript - Angular 复选框未正确绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31172067/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com