使用angularJs选择默认值的最简单方法是什么?
我有这个控制权:
<div class="col-md-1">
<label for="timeZone">Time zone</label>
<select id="timeZone" name="timeZone" class="form-control"
ng-model="newTestSessionCtrl.formData.timeZoneValues"
ng-options="timeZone.name for timeZone in newTestSessionCtrl.viewData.timeZoneValues">
<option value="" disabled selected>Select</option>
</select>
</div>
在我的控制器中,我确定了像这样的timeZoneValues:
timeZoneValues: [{value: "UTC", name: "UTC"}, {value: "UTC+1", name:"UTC+1"}]
我尝试做的是使用ng-init。就像它解释here但我猜我做错了。
我要做的是默认选择UTC。
答案 0 :(得分:0)
这是工作吗?
<div class="col-md-1">
<label for="timeZone">Time zone</label>
<select id="timeZone" name="timeZone" class="form-control"
ng-model="newTestSessionCtrl.formData.timeZoneValues"
ng-init="newTestSessionCtrl.formData.timeZoneValues = timeZone[0]"
ng-options="timeZone.name for timeZone in newTestSessionCtrl.viewData.timeZoneValues">
<option value="" disabled selected>Select</option>
</select>
</div>
答案 1 :(得分:0)
删除空选项:
<div class="col-md-1">
<label for="timeZone">Time zone</label>
<select id="timeZone" name="timeZone" class="form-control"
ng-model="selected"
ng-options="timeZone as timeZone.name for timeZone in newTestSessionCtrl.viewData.timeZoneValues">
</select>
</div>
并在javascript添加
$scope.selected = timeZoneValues[0].name;
答案 2 :(得分:0)
我遇到了同样的问题,这就是我解决的问题:
这是html代码:
<div class="col-md-1">
<label for="timeZone">Time zone</label>
<select ng-model="defaultValue" ng-options="timeZone.name for timeZone in newTestSessionCtrl.viewData.timeZoneValues" ></select>
</div>
在控制器中,我将默认值设置为数组的第一个值:
$scope.defaultValue = $scope.timeZoneValues[0].name;
希望这有帮助
答案 3 :(得分:0)
将控制器中的默认值分配给ng-model:
timeZoneValues: [{value: "UTC", name: "UTC"}, {value: "UTC+1", name:"UTC+1"}];
newTestSessionCtrl.formData.timeZoneValues = "UTC";
newSessionCtrl需要是你用来从控制器引用控制器本身的任何东西,如果你不是,则需要用作范围。
另外,您可以使用:
<div class="col-md-1">
<label for="timeZone">Time zone</label>
<select id="timeZone" name="timeZone" class="form-control"
ng-model="newTestSessionCtrl.formData.timeZoneValues"
ng-options="timeZone.name for timeZone in newTestSessionCtrl.viewData.timeZoneValues"
ng-init="newTestSessionCtrl.formData.timeZoneValues = newTestSessionCtrl.viewData.timeZoneValues[0].name">
</select>
</div>
答案 4 :(得分:0)
您错过了在select标记中的ng-init指令内分配值。请参阅以下工作plnkr
http://plnkr.co/edit/SBrSUjrfWHJvkufVjSJG?p=preview
HTML:
<body ng-controller="MainCtrl">
<div class="col-md-1">
<label for="timeZone">Time zone</label>
<select id="timeZone" name="timeZone" class="form-control" ng-init="timeZoneModel = timeZoneValues[0]"
ng-model="timeZoneModel"
ng-options="timeZone.name for timeZone in timeZoneValues">
<option value="" disabled selected>Select</option>
</select>
</div>
</body>
JS:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.timeZoneValues = [{value: "UTC", name: "UTC"}, {value: "UTC+1", name:"UTC+1"}];
});