簡體   English   中英

預選 <option>在<select>在使用ng-repeat時

[英]Preselect <option> in <select> while using ng-repeat

我正在使用AngularJS和HTML。 如果使用ng-repeat生成我的選項,是否可以在選項標簽中預先選擇一個選項? 例如,請參見下面的代碼片段:

HTML:

<select class="form-control" id="eventSelectMenu">
    <option ng-repeat="option in allEventData">{{option.name}}</option>
</select>

我已經嘗試過在這里這里介紹的解決方案,但是都沒有成功。

感謝您提供的任何建議!

您可以嘗試使用此語法。 另外,您需要使用ng-model,它將為您提供五個您需要選擇的值:

<select class="form-control"
        ng-model="yourmodel"
        ng-options="option for option in allEventData">
     </select>

您可以設置任何應預先選擇為select的ngModel值的ngModel

 console.clear(); angular.module('so-answer', []) .controller('ctrl', ['$scope', function($scope) { $scope.options = [1, 2, 3, 4, 5, 6]; $scope.selected = 3; } ]) 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="so-answer" ng-controller="ctrl"> <select ng-model="selected" ng-options="opt for opt in options"></select> </div> 

除了已經發布的答案之外,我還將添加此答案。 此示例演示如何使用對象數組進行選擇。 在這種情況下,假設allEventData中的事件具有namevalue屬性。 相應地適應您的情況

 angular.module("app", []) .controller("controller", function($scope){ $scope.allEventData = [ { value: 1, name: "Event 1" }, { value: 2, name: "Event 2" }, { value: 3, name: "Event 3" } ] $scope.selectedEventValue = 3 }) 
 <!DOCTYPE html> <html ng-app="app" ng-controller="controller"> <head> <script data-require="angularjs@1.5.7" data-semver="1.5.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script> <link rel="stylesheet" href="style.css" /> <script src="script.js"></script> </head> <body> <select class="form-control" id="eventSelectMenu" ng-model="selectedEventValue" ng-options="item.value as item.name for item in allEventData"> </select> <pre>Selected Value: {{selectedEventValue}}</pre> </body> </html> 

您應該能夠像這樣直接綁定屬性

<option ng-repeat="option in allEventData" selected={{option.selected}}>{{option.name}}</option>

類似的答案

我喜歡這個:

<select id="test"
                    name="test"
                    ng-model="vm.form.existing"
                    ng-options="item.value as item.title for item in vm.existingData">
            </select>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM