使用数组中的嵌套对象在AngularJS中切换数据模型以获取动态选择菜单

时间:2013-11-20 04:15:19

标签: javascript angularjs

采用所提问题的概念here,并使用此代码:

标记:

<div ng-app="myApp" ng-controller="BookingCtrl">
<select ng-model="selected.site" ng-options="s.data as s.site for s in data">
    <option value="">-- Site --</option>
</select>
<select ng-model="selected.building" ng-options="b.data as b.building for b in selected.site.buildings">
    <option value="">-- Building --</option>
</select>
<select ng-model="selected.floor" ng-options="f.data as f.floor for f in selected.site.floors">
    <option value="">-- Floor --</option>
</select>

的javascript:

var myApp = angular.module( 'myApp', [] );

myApp.controller('BookingCtrl',['$ scope','$ location',函数($ scope,$ location){

$scope.selected = {};

$scope.data = [
    {
        "id" : "0",
        "site" : "Brands Hatch",
        "data" : 0,
        "buildings" : [
            { "building" : "Building #1", "data":1},
            { "building" : "Building #2", "data":2 },
            { "building" : "Building #3", "data":3 }
        ],
        "floors" : [
            { "floor" : "Floor #1", "data":1 },
            { "floor" : "Floor #2", "data":2 },
            { "floor" : "Floor #3", "data":3 }
        ]
    },{
        "id" : "1",
        "site" : "Silverstone",
        "data" : 1,
        "buildings" : [
            { "building" : "Building #4", "data":1 },
            { "building" : "Building #5", "data":2 },
            { "building" : "Building #6", "data":3 }
        ],
        "floors" : [
            { "floor" : "Floor #4", "data":1 },
            { "floor" : "Floor #5", "data":2 },
            { "floor" : "Floor #6", "data":3 }
        ]
    }
];

}]);

随附fiddle

如何根据另一个选择的选择更改其他选择下拉菜单的ng-options?

我所做的就是为每个对象添加一个“data”属性并更新ng-option。

1 个答案:

答案 0 :(得分:1)

我在这里更新了你的小提琴:

http://jsfiddle.net/Pb8GL/1/

我已经编辑了你的html:

<div ng-app="myApp" ng-controller="BookingCtrl">
    <select ng-model="selected.site" ng-options="s.data as s.site for s in data" ng-change="updateSelectedBuildingsAndFloors()">
        <option value="">-- Site --</option>
    </select>
    <select ng-model="selected.building" ng-options="b.data as b.building for b in selectedBuildings">
        <option value="">-- Building --</option>
    </select>
    <select ng-model="selected.floor" ng-options="f.data as f.floor for f in selectedFloors">
        <option value="">-- Floor --</option>
    </select>
</div>

并在Javascript中添加了ng-change功能:

$scope.updateSelectedBuildingsAndFloors = function(){
    $scope.selectedDataArray = $scope.data.filter(function (data) { return data.data == $scope.selected.site });        
    $scope.selectedData = $scope.selectedDataArray[0];
    $scope.selectedBuildings = $scope.selectedData.buildings;        
    $scope.selectedFloors = $scope.selectedData.floors;        
}   

如果有帮助,请告诉我,

乌卢格别克

更新

新jsfiddle,说明没有选定网站的情况:http://jsfiddle.net/Pb8GL/2/