我想创建一个带有“selected”值的select标签。我使用 ng-repeat 执行此操作,因为我无法向 ng-options 添加自定义指令。这是代码。
<select class="ng-valid ng-dirty" ng-model="selectedCity">
<option ng-repeat="city in allCities" value="{{city.id}}" after-render-cities>{{city.name}}</option>
</select>
这会增加一个额外的选项,其值为??string:1?我搜索了很多。由于 ng-options 解决了这个问题,因此我必须为每个选项添加指令 after-render-cities 。我该如何解决这个问题?
答案 0 :(得分:1)
使用此
<select class="ng-valid ng-dirty" ng-model="selectedCity" ng-options="city.id as city.name for city in allCities">
</select>
用于选择第一个值,在控制器中写下以下代码
$scope.selectedCity = $scope.allCities[0].id;
答案 1 :(得分:0)
使用ng-init解决值=?string:1?
com.google.firebase.quickstart.analytics V/FA: Session started, time: 918306437
com.google.firebase.quickstart.analytics D/FA: Logging event (FE): _s, Bundle[{_o=auto}]
com.google.firebase.quickstart.analytics V/FA: Using measurement service
com.google.firebase.quickstart.analytics V/FA: Connecting to remote service
com.google.firebase.quickstart.analytics D/FA: Connected to remote service
com.google.firebase.quickstart.analytics V/FA: Processing queued up service tasks: 1
com.google.firebase.quickstart.analytics V/FA: Inactivity, disconnecting from AppMeasurementService
另一种选择,你可以使用ng-selected fiddle
<select class="ng-valid ng-dirty" ng-model="selectedCity" ng-init='selectedCity=allCities[0].id'>
<option ng-repeat="city in allCities" value="{{city.id}}" after-render-cities>{{city.name}}</option>
</select>
答案 2 :(得分:0)
试试此代码
Java脚本
var app = angular.module('myApp', []);
app.controller('SampleController', function ($scope) {
$scope.Cities = [
{ Id: 1, Name: "New York" },
{ Id: 2, Name: "Colombo" },
{ Id: 3, Name: "Real Madrid" },
{ Id: 4, Name: "Bostan" },
{ Id: 5, Name: "Birmingham" }
];
$scope.City= 3;
});
HTML
<select ng-options="C.Id as C.Name for C in Cities" ng-model="City"></select>
答案 3 :(得分:0)
您可以使用directive
和select
创建自定义ng-options
。
<强>段强>:
JS:
template: "<select ng-options='item.id as item.name for item in list' ng-model='data'></select>",
HTML:
<div select-option list="list" ng-model='data'></div>
请参阅演示here。