答案 0 :(得分:2)
我已编辑了您的代码,如下所示。
需要注意的几点:
ng-init
,因为这不是一个好习惯,不强烈推荐。ngInit的唯一合适用途是用于别名ngRepeat的特殊属性。除了这种情况,您应该使用控制器而不是ngInit来初始化范围
上的值
ng-switch
会创建自己的子范围。因此,您的模型没有直接绑定到控制器。您可以绑定模型或使用控制器作为语法,如下所示。作为语法的控制器隐含地处理DOT规则。有关详细参考,请参阅JavaScript Prototypal Inheritance。
angular.module("MyApp", []).controller("MyCtrl", function() {
var vm = this;
vm.cities = [{
'name': 'City 1',
'value': 1
}, {
'name': 'City 2',
'value': 2
}];
vm.createSurburbArray = function() {
vm.suburbs = [{
'name': vm.City + ': Suburb 1',
'value': 1
}, {
'name': vm.City + ': Suburb 2',
'value': 2
}];
}
//init
function init() {
vm.Page = 4;
};
init();
});
<!DOCTYPE html>
<html>
<head>
</head>
<body ng-app="MyApp" ng-controller="MyCtrl as vm">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<div ng-switch="vm.Page">
<div ng-switch-when="4">
<select ng-model="vm.City" ng-options="city.name as city.name for city in vm.cities" ng-change="vm.createSurburbArray()">
<option value="" disabled="disabled">---City---</option>
</select>
<br><br>{{vm.City}}{{vm.Suburb}}
<select ng-model="vm.Suburb" ng-options="suburb.name as suburb.name for suburb in vm.suburbs">
<option value="" disabled="disabled">---Course---</option>
</select>
</div>
</div>
</body>
</html>
答案 1 :(得分:1)
VIVZ对此线索有更好的回答
然而,这是一个更简单的版本,如何从提问者的代码中修复/理解问题。
1:将“ng-value”更改为“value”
2:将default-option和init值更改为“”(而不是“0”)
<!DOCTYPE html>
<html>
<head>
</head>
<body ng-app>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<div ng-switch="Page" ng-init="Page = 4">
<div ng-switch-when="4">
<select ng-model="City" ng-init="City=''" ng-change="Suburb=''">
<option value="" disabled="disabled">---City---</option>
<option>City 1</option>
<option>City 2</option>
</select>
<br><br>
<select ng-model="Suburb" ng-init="Suburb=''">
<option value="" disabled="disabled">---Course---</option>
<option ng-show="City == 'City 1'">City 1: Suburb 1</option>
<option ng-show="City == 'City 1'">City 1: Suburb 2</option>
<option ng-show="City == 'City 2'">City 2: Suburb 1</option>
<option ng-show="City == 'City 2'">City 2: Suburb 2</option>
</select>
{{City}}
</div>
</div>
</body>
</html>