繁体   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