您好我正在开发angularjs中的Web应用程序。我有一个表格,我把dropdownlistbox。下面是我用数组填充dropdownboxlist的代码。
<select class="with-icon" ng-model="user.period" name="period" id="period" ng-options="user.ID as user.period for user in periodList" required>
<option value="" label="{{ 'Period' | translate }}">{{ 'Period' | translate }}</option>
</select>
以下是我的JS代码。
$scope.periodList = [{ ID: 1, period: '1 Month' }, { ID: 2, period: '2 Month' }, { ID: 3, period: '3 Month' }, { ID: 4, period: '4 Month' }, { ID: 5, period: '5 Month' }, { ID: 6, period: '6 Month' }];
我尝试默认设置第一个值,如下所示。
$scope.user.period = [{ ID: 1, period:'1 Month' }];
这种方法对我不起作用。
我尝试了以下方法$scope.user.period=1;
,即使这对我不起作用。
我试过$scope.user.period = $scope.periodList[1];
,这也适合我。有人可以帮我设置正确的方法来默认选择第一个值。任何帮助,将不胜感激。谢谢。
答案 0 :(得分:2)
与$scope.user.period = 1;
合作正常。也许你忘了先把用户声明为对象
$scope.user = {};
$scope.user.period = 1;
angular.module("app",[])
.controller("ctrl",function($scope){
$scope.periodList = [{ ID: 1, period: '1 Month' }, { ID: 2, period: '2 Month' }, { ID: 3, period: '3 Month' }, { ID: 4, period: '4 Month' }, { ID: 5, period: '5 Month' }, { ID: 6, period: '6 Month' }];
$scope.user = {};
$scope.user.period = 1;
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<select class="with-icon" ng-model="user.period" name="period" id="period" ng-options="user.ID as user.period for user in periodList" required>
<option value="" label="{{ 'Period' }}">{{ 'Period' }}</option>
</select>
</div>
答案 1 :(得分:1)
尝试将其设置为:
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.user = {};
$scope.periodList = [{ ID: 1, period: '1 Month' }, { ID: 2, period: '2 Month' }, { ID: 3, period: '3 Month' }, { ID: 4, period: '4 Month' }, { ID: 5, period: '5 Month' }, { ID: 6, period: '6 Month' }];
$scope.user.period = $scope.periodList[0].ID;
});
&#13;
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select class="with-icon" ng-model="user.period" name="period" id="period" ng-options="user.ID as user.period for user in periodList" required>
<option value="" label="{{ 'Period'}}">{{ 'Period'}}</option>
</select>
{{user.period}}
</div>
&#13;
答案 2 :(得分:1)
你可以使用这样的东西
<select ng-init="somethingHere = periodList[0]"> ... </select>
答案 3 :(得分:0)
根据文档,您需要将copy
指定为用于创建您想要预选的选项的列表中的项目。在这种情况下,ng-model
中的第一项。
$scope.periodList
您可以在此处找到更多信息:https://docs.angularjs.org/api/ng/directive/ngOptions