如何通过父/子模型分配默认 ngOptions
?
In this question OP 展示了一种使用 ngOptions
模板
<select ng-model="x.site" ng-options="s.site for s in data"></select>
<select ng-model="x.name" ng-options="b.name for b in x.site.buildings"></select>
控制者
$scope.x = {};
$scope.data = [
{
"site" : "Brands Hatch",
"buildings" : [
{ "name" : "Building #1" },
{ "name" : "Building #2" },
{ "name" : "Building #3" }
]
},{
"site" : "Silverstone",
"buildings" : [
{ "name" : "Building #4" },
{ "name" : "Building #5" },
{ "name" : "Building #6" }
]
}
];
您将在 中看到的内容 this fork 是下拉菜单没有任何默认值 --- 也就是说,默认选项是“空白”。在正常用例中,这不是问题,并且可以通过解释得很好的 Controller 轻松配置默认选项 in the docs .
- 如何使用
ngOptions
消除父/子模型的“空白”选项? - 如何通过 View 或通过 Controller 动态选择默认选项。 请务必记住,子默认选择选项首先取决于父选择的选项。
最佳答案
空白项是由空模型值引起的。您可以尝试将以下代码放在 Controller 的末尾。诀窍是在加载页面时以及 site 值时初始化 site、building 和 floor被改变了。希望对您有所帮助。
$scope.selected = {
site: $scope.data[0],
building: $scope.data[0].buildings[0],
floor: $scope.data[0].floors[0]
};
$scope.$watch('selected.site', function () {
console.log($scope.selected.site);
$scope.selected = {
site: $scope.selected.site,
building: $scope.selected.site.buildings[0],
floor: $scope.selected.site.floors[0]
};
});
关于javascript - 父/子模型 AngularJS 上的默认 ngOptions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18022682/