AngularJS三级联动下拉框无法读取JSON数据求助
解决AngularJS三级联动下拉框第三级数据无法获取的问题
我来帮你搞定这个三级联动的问题!看了你的代码后,发现两个关键问题导致第三级区域选项出不来:
问题1:第三级下拉框的ng-options语法错误
你第三个下拉框的ng-options写得完全不对,根本没有关联到选中城市的Area数据,正确的写法应该是遍历选中城市的Area数组,把每个区域的title作为显示文本。
问题2:JSON数据里的字段不统一
在Washington州下的第一个城市The Little Fishing Village的Area数组中,第三个对象用了Name字段而不是统一的title,这会导致这个区域选项显示异常,得改成title才能正常识别。
下面是修正后的完整代码:
修正后的JavaScript代码
var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.states = [{ 'Name': 'Oregon', 'Population': 4093465, 'Cities': [{ 'Name': 'Portland', 'Population': 639863, 'Area': [{ 'title': 'East Portland', 'Population': 5000, }, { 'title': 'west Portland', 'Population': 8000, }, { 'title': 'North Portland', 'Population': 6000, }, { 'title': 'south Portland', 'Population': 5000, }] }, { 'Name': 'Salem', 'Population': 167419, 'Area': [{ 'title': 'East Salem', 'Population': 5000, }, { 'title': 'West Salem', 'Population': 6000, }, { 'title': 'North Salem', 'Population': 8000, }, { 'title': 'South Salem', 'Population': 10000, }] }] }, { 'Name': 'Washington', 'Population': 7288000, 'Cities': [{ 'Name': 'The Little Fishing Village', 'Population': 704352, 'Area': [{ 'title': 'East Little Fishing Village', 'Population': 5000, }, { 'title': 'West Little Fishing Village', 'Population': 6000, }, { // 这里把Name改成了title,统一字段名 'title': 'North Little Fishing Village', 'Population': 8000, }, { 'title': 'South Little Fishing Village', 'Population': 10000, }] }, { 'Name': 'Vancouver', 'Population': 174826, 'Area': [{ 'title': 'East Vancouver', 'Population': 12000, }, { 'title': 'West Vancouver', 'Population': 18000, }, { 'title': 'North Vancouver', 'Population': 25000, }, { 'title': 'South Vancouver', 'Population': 35000, }] }] }]; });
修正后的HTML代码
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp" ng-controller="myCtrl"> <label for="name">Select a State:</label> <select id="name" ng-model="selectedName" ng-options="state as state.Name for state in states"></select> <br /> <label for="region">Select a City:</label> <!-- 新增ng-disabled,未选中州时禁用城市下拉框 --> <select id="region" ng-model="selectedCity" ng-options="item as item.Name for item in selectedName.Cities" ng-disabled="!selectedName"></select> <label for="area">Select a Area:</label> <!-- 修正ng-options语法,新增ng-disabled --> <select id="area" ng-model="selectedAreaName" ng-options="area as area.title for area in selectedCity.Area" ng-disabled="!selectedCity"></select> <br /><br /> <!-- 用?.可选链避免未选中时的报错 --> <p>{{selectedName?.Name}}</p> <p>{{selectedName?.Population}}</p> <p>{{selectedCity?.Name}}</p> <p>{{selectedCity?.Population}}</p> <p>{{selectedAreaName?.title}}</p> <p>{{selectedAreaName?.Population}}</p> </div>
另外我还加了两个实用优化:
- 给第二、三级下拉框加上
ng-disabled,避免用户在未选中上一级时误操作 - 使用
?.可选链操作符,防止未选中选项时页面出现控制台报错
这样修改后,三级联动就能正常工作,第三级区域选项也能正确加载出来啦~
内容的提问来源于stack exchange,提问作者Code lover
相关产品推荐
相关产品推荐

