javascript - 父/子模型 AngularJS 上的默认 ngOptions

标签 javascript angularjs

如何通过父/子模型分配默认 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 值时初始化 sitebuildingfloor被改变了。希望对您有所帮助。

$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/

相关文章:

javascript - 如何跟踪indexedDB中的ADD错误?

android - 将 ng-href 与 geo : Uri in Cordova does not work 一起使用

javascript - 在 Canvas 上绘制多边形形状并允许在其上显示工具提示

javascript - 从 Controller 获取数据到 AngularJs 组件

javascript - AngularJS - 从代码重定向到另一个域

javascript - Angular JS : Unable to set value to ng-model variable inside ng-repeat

javascript - 将显示值格式传递给 Angular 分量

javascript - 在 Materialise 中添加新幻灯片

javascript - 将 Base64 图像字符串转换回文件以发送到 Parse upload

javascript - 查询阻止从 php 提交响应时的表单