在ng个选项中选择一个选项不使用jQuery

Select an Option in ng-options Not working with jQuery

本文关键字:选项 一个 jQuery ng 选择      更新时间:2023-09-26

我正试图使用jquery,根据基于变量中文本生成的选项标签,在ng个选项中选择一个选项。

$scope.storedDay = 'Today';
<select id="selectedDay" name="selectedDay" class="form-control" ng-model="selectedDay" ng-options="day.text for day in days"></select>
$('#selectedDay option[label="' + $scope.storedDay + '"]').prop('selected', true);

生成的HTML

<select id="selectedDay" name="selectedDay" class="form-control ng-pristine ng-untouched ng-valid" ng-model="selectedDay" ng-options="day.text for day in days" tabindex="0" aria-invalid="false">
<option value="?" selected="selected"></option>
<option value="object:35" label="Today">Today</option>
<option value="object:36" label="Tomorrow">Tomorrow</option>
<option value="object:37" label="Sunday">Sunday</option>
</select>

它从未被选中。即使我在标签文本中硬编码。

您可以使用angular的jqLite迭代选项并比较它们的标签来实现这一点,请参阅以下工作小提琴:

//Iterate over options
for (var i = 0; i < angular.element(document.querySelector('#selectedDay').children).length; i++) {
    if (angular.element(document.querySelector('#selectedDay').children[i]).attr('label') == $scope.storedDay) {
        //Set selected option in ng-model
        $scope.selectedDay = angular.element(document.querySelector('#selectedDay').children[i]).attr('value');
    }
}

http://jsfiddle.net/hmartos/sjsk71w8/

我只需要在ng options=FAIL:}中添加track by day.text