AngularJS无法获取下拉菜单的选定索引

时间:2018-09-19 13:59:27

标签: javascript jquery angularjs

我有这个下拉菜单:

<select class="form-control" name="timeSlot" ng-model="user.dateTimeSlot" ng-change="dateTimeChanged(user.dateTimeSlot)" ng-blur="blur29=true" required style="float: none; margin: 0 auto;">

                                            <option ng-repeat="x in dateTimeSlots"
                                                    ng-disabled="x.taken"
                                                    ng-value="x.timeSlot">
                                                {{x.dateSlot}}
                                            </option>

                                        </select>

我正在尝试获取ng-change上的选定索引。但是它总是返回-1

$scope.dateTimeChanged = function (selectedItem) {

        var index = $scope.dateTimeSlots.indexOf(selectedItem);

        console.log(index);

    }

为什么总是返回-1。...这是我的数据的屏幕截图:

enter image description here

我想做的是获取所选项目的ID值。我在做什么错了?

1 个答案:

答案 0 :(得分:1)

好吧,这确实不确定您真正想要什么。在我看来,您正在尝试两匹马:)将ng-model绑定到timeSlot,但是您真正想要的是索引,这样您就可以更轻松地抓住对象?将选项值直接绑定到索引怎么办? :

<option ng-repeat="x in dateTimeSlots"
   ng-disabled="x.taken"
   ng-value="{{ $index }}"> <!-- here -->
    {{x.dateSlot}}
</option>

现在user.dateTimeSlot将为0、1、2、3,依此类推(选择选项时)。在change方法中,您现在收到索引

$scope.dateTimeChanged = function(selectedItem) {
  console.log($scope.dateTimeSlots[selectedItem]) //<-- the selected object by index
}