Angular.js 在 input:checkbox 中将 ng-model 与 ng-repeat 绑定

Angular.js Bind ng-model with ng-repeat in input:checkbox

我有一个应用程序使用 Angularjs v1.69 我得到一个 Json 的时隙响应 以下是当前代码:

$scope.TimeSlotList = JSON.parse(localStorage.getItem("TimeSlots"));
Console.log($scope.TimeSlotList);

输出:

[
{
    "id": 1,
    "time": "7am - 10am"
},
{
    "id": 2,
    "time": "10am - 1pm"
},
{
    "id": 3,
    "time": "1pm - 4pm"
},
{
    "id": 4,
    "time": "4pm - 7pm"
},
{
    "id": 5,
    "time": "7pm - 10pm"
}
]

这是在部分

中完成的
        <div class="col-md-6">
                <div class="form_pad20">
                    <label>Prefered Time</label>
                    <div class="clearfix">
                        <div class="form-field field-destination">
                            <div class="radio-checkbox display_inline" ng-repeat="x in TimeSlotList">
                                <input id="check-{{x.id+9}}" type="checkbox" class="checkbox" ng-model="TimeSlotList[$index]">
                                <label for="check-{{x.id+9}}">{{x.time}}</label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

所需的输出是 selected 的复选框,我想要那个值 例如:如果用户 select 时隙 2 和 3 我想发送 23 到后端 即 Timeslot-2 和 Timeslot-3 应该 return true 或者其他我想要输出为

var FinalTime="23";

试图找出过去 2 天的数据 但经过几次尝试,基本上最好的解决方案是

ng-model="TimeSlot-{{x.id}}"

但这会导致错误

Error: [ngModel:nonassign] Expression 'ScdItem.TSlot(x.id)' is non-assignable.

请问有人能帮帮我吗?

更改 TimeSlotList 使其包含 selected 字段。初始值可以设置为false.

$scope.TimeSlotList = JSON.parse(localStorage.getItem("TimeSlots"));
$scope.TimeSlotList.forEach(item => item.selected = false);

然后使用 ng-model:

selected 字段绑定到相应的复选框
<input id="check-{{x.id+9}}" type="checkbox" class="checkbox" ng-model="x.selected">

这将根据 checked/not 选中的复选框更改 selected 的值。当你向服务器发送数据时,你可以根据 selected 字段的值提取插槽的 ID,如下所示:

var selectedSlots = $scope.TimeSlotList
  .filter(slot => slot.selected) // Get all the selected slots
  .map(slot => slot.id) // Extract IDs of the slots
  .join(''); // Join the IDs to form a string

这样 selectedSlots 将包含所选广告位的 ID。

<div class="col-md-6">
            <div class="form_pad20">
                <label>Prefered Time</label>
                <div class="clearfix">
                    <div class="form-field field-destination">
                        <div class="radio-checkbox display_inline" ng-repeat="x in TimeSlotList">
                            <input id="check-{{x.id+9}}" type="checkbox" class="checkbox" ng-model="x.id" ng-change="checkTimeslot(x.id)">
                            <label for="check-{{x.id+9}}">{{x.time}}</label>
                        </div>
                    </div>
                </div>
            </div>