在AngularJS中选择依赖下拉列表的默认值

时间:2017-07-15 20:12:01

标签: javascript angularjs drop-down-menu

我需要预先选择两个相关下拉列表的默认值。因此,在页面加载时,下拉列表应显示类似于" Automative"用"两轮车"选择。 (并且不使用selected属性,必须通过$ scope加载默认值) 下面是工作下拉列表的Plunkr链接。

http://plnkr.co/edit/3Xrpb4jBziWNZE9JVfts?p=preview

<select class="home_search_select" name="d1" ng-model="selectedd1" ng-options="cat.category_id as cat.category_name for cat  in categorydata track by cat.category_id" id="d1">
   <option value="">Select Category</option>
</select>

<select class="home_search_select" name="d2" id="d2" ng-disabled="!selectedd1" ng-model="selectedd2" ng-options="subcat.ID as subcat.Name for subcat in ((categorydata|filter:{'category_id':selectedd1})[0].Subcategory) track by subcat.ID">
  <option class="home_search_select" value="">Select Sub Category</option>
</select>

1 个答案:

答案 0 :(得分:0)

为selected1指定值,如下所示

$scope.selectedd1= {
    "category_name": "Automotive",
    "category_id": "1",
    "Subcategory": [{
      "Name": "Two Wheeler",
      "ID": "1"
    }, {
      "Name": "Four Wheeler",
      "ID": "2"
    }, {
      "Name": "Heavy Moving Vehicles",
      "ID": "3"
    }, {
      "Name": "Automobile Related",
      "ID": "4"
    }]
  };

修改第二个下拉列表中的ng-options

<select class="home_search_select" name="d2" id="d2"
    ng-disabled="!selectedd1" ng-model="selectedd2" 
    ng-options="subcat.ID as subcat.Name for subcat in selectedd1.Subcategory track by subcat.ID">
      <option class="home_search_select" value="">Select Sub Category</option>
 </select>

要在下拉列表中使用ng-change指令

来收听更改
<select class="home_search_select" name="d1" 
ng-model="selectedd1" 
ng-change="homeChanged()"
ng-options="cat as cat.category_name for cat  in categorydata track by cat.category_id" id="d1">
  <option ng-value="">Select Category</option>
</select>

注意:ng-options已更改为包含整个对象

<强> Updated Plunker