我有以下选择选项:
<select ng-model="class_name" name="class_name" class="form-control">
<option ng-repeat="t in MemberClass" value="{{t}}">{{t.class_name}}</option>
</select>
我想设置默认选项 MemberClass [0] 来选择选项。我尝试了以下代码,但没有工作。
JSON数据来自Webservice ...
//To fetch Member Class
$http.get('http://192.168.1.6:8080/apartment//member/class/list').then(function(response) {
$scope.MemberClass = response.data.list;
$scope.class_name = $scope.MemberClass[0]; // Not working
});
成员类JSON数据是:
[
{
"class_id": 1,
"class_name": "Owner",
"class_details": "DCE"
},
{
"class_id": 7,
"class_name": "Staff "
},
{
"class_id": 10
"class_name": "Vendor"
}
]
Plunker示例:https://plnkr.co/edit/vVcrmOREkcVBBM2Ynhgv?p=preview (如果我没有选择任何选项,我会收到错误...)
答案 0 :(得分:1)
您可以使用ng-options
。这是大多数时候的首选方式。像这样:
<select ng-model="class_name" ng-options="t as t.class_name for t in MemberClass">
</select>
现在,由于您已将$scope.class_name
指定为默认值,因此它已被选中。
答案 1 :(得分:1)
使用ng-init
。试试如下。
<!DOCTYPE html>
<html ng-app="myApp" ng-controller="Ctrl">
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div class="form-group">
<label class="control-label col-md-3">Member Class </label>
<div class="col-md-4">
<select ng-model="class_name"
ng-init=" class_name = MemberClass[0]" name="class_name" ng-options="t as t.sub_class_name for t in MemberClass">
</select>
<p>Selected Value: {{class_name}} <p>
</div>
</div>
<button type="submit" ng-click="alertdata()">Save</button>
<script>
angular.module('myApp', [])
.controller('Ctrl', function($scope) {
var MemberClass;
$scope.MemberClass = [{
"sub_class_id": 1,
"sub_class_name": "Primary"
},
{
"sub_class_id": 2,
"sub_class_name": "Secondary "
},
{
"sub_class_id": 3,
"sub_class_name": "Dependent "
},
{
"sub_class_id": 4,
"sub_class_name": "Sub Member"
},
{
"sub_class_id": 5,
"sub_class_name": "None"
}
]
// $scope.class_name = $scope.MemberClass[0];
$scope.alertdata = function() {
$scope.class_name = "{}";
var parameter;
parameter = {
"member": {
"first_name": "first_name",
"role": [{
"role_id": 4
}],
"associated": "associated",
"class0": [JSON.parse($scope.class_name)],
"contect": [{
"intercom": "intercom"
}],
"individualdetails": [{
"gender": "gender"
}]
},
"address": [{
"street_address_1": "street_address_1"
}]
}
console.log(JSON.stringify(parameter));
};
});
</script>
</body>
</html>
答案 2 :(得分:0)
你应该明确地使用ng-options来实现这个
<select ng-model="class_name" ng-options="t as t.class_name for t in MemberClass">
</select>
要设置默认值,请将$ scope.class_name设置为MemberClass数组的值,或者您可以添加如下所示的空选项标记,当$ scope.class_name为null时将选择该标记
<select ng-model="class_name" ng-options="t as t.class_name for t in MemberClass">
<option value="">Select value</option>
</select>