Angular.js在输入中使用ng-repeat绑定ng-model:复选框

时间:2018-03-29 05:38:45

标签: javascript angularjs angularjs-ng-repeat

我有一个使用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>

必需输出是选择了哪个复选框我想要该值 对于Ex:如果用户选择时隙2和3 我想把23送到后端 即Timeslot-2和Timeslot-3应该返回true 或其他我想要输出

var FinalTime="23";

试着弄清楚过去2天 但是很少尝试基本上是最好的解决方案

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

但是通过错误

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

请有人帮助我吗?

2 个答案:

答案 0 :(得分:2)

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

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

然后使用selected

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

这将更改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。

答案 1 :(得分:0)

<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>
相关问题