简体   繁体   中英

Select an Option in ng-options Not working with jQuery

I am trying to select an option in ng-options using jquery based on the options label being generated based upon the text in a variable.

$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);

Generated 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>

It is never selected. Even if I hard code in the label text.

You can do this using angular's jqLite iterating over options and comparing their labels, see the following working fiddle:

//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添加track by day.text

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM