我正在尝试创建下拉列表,它根据国家/地区填充州,根据城市填充城市,但最初在页面加载时它包含以前从数组中提取的数据。尝试调用 GetSelectedCountry 和 GetSelectedState 函数时由于包含在 ng 中的 mydata 而无法正常工作- 下拉列表中的模型和虚拟数组值在页面加载时不显示。以下是我的虚拟代码。
<head>
<!--ajax library-->
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script>
//angular module code
angular
.module('myApp', [])
.run(function($rootScope) {
$rootScope.title = 'myTest Page';
})
.controller('testController', ['$scope',
function($scope) {
//dummy array data
$scope.mydata = [
{ "cID": 1014,"country": "USA","state" :"California"}
];
//country json to get selected state and city based on country
$scope.countries = {
'USA': {
'Alabama': ['Montgomery', 'Birmingham'],
'California': ['Sacramento', 'Fremont'],
'Illinois': ['Springfield', 'Chicago']
},
'Australia': {
'New South Wales': ['Sydney'],
'Victoria': ['Melbourne']
}
};
$scope.GetSelectedCountry = function() {
$scope.strCountry = $scope.country;
};
$scope.GetSelectedState = function() {
$scope.strState = $scope.state;
};
}
])</script></head>
<!--HTML Code-->
<body ng-app="myApp">
<div ng-controller="testController"> <label for="country">Country
*</label> <select id="country" name="country" ng-model="mydata .country" ng-options="country for (country, states) in countries"
ng-change="GetSelectedCountry()">
<option value=''>Select</option></select> <label for="state">State *</label> <select id="state"
ng-disabled="!country" name="state" ng-model="mydata.state"
ng-options="state for (state,city) in country"
ng-change="GetSelectedState()">
<option value=''>Select</option></select> <label for="city">City *</label> <select id="city" ng-disabled="!country
|| !state" ng-model="city" ng-options="city for city in state">
<option value=''>Select</option>
</select>
</div>
</body>
最佳答案
因为您在 ng-model 中使用 mydata.country 和 mydata.state,所以在脚本中您可以通过
$scope.GetSelectedCountry = function() {
$scope.strCountry = $scope.mydata.country;
};
$scope.GetSelectedState = function() {
$scope.strState = $scope.mydata.state;
};
否则只需在您的 html 中为国家和州更改 ng-model 名称
<select id="country" name="country" ng-model="country" ng-options="country for (country, states) in countries"
ng-change="GetSelectedCountry()">
<option value=''>Select</option></select> <label for="state">State *</label>
<select id="state" ng-disabled="!country" name="state" ng-model="state" ng-options="state for (state,city) in country"
附加一个有效的plunker
关于javascript - 函数调用后虚拟数组值未填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46975358/