Angular:根据模型依赖性将Drop Down项激活

时间:2014-10-01 15:18:11

标签: angularjs ng-options

我希望一个下拉列表中的项目的活动状态取决于第二个模型的属性:

angular.module('mainApp')
  .controller('MainCtrl', function($scope) {
  $scope.departments = [
    {id:0, name: 'Dry Goods'},
    {id: 1, name:'Frozen Food'},
    {id: 2, name:'Electronics'}
  ];
  $scope.categories = [
    {id: 0, name: 'cereal', departmentId: 0},
    {id: 1, name: 'cookies', departmentId: 0},
    {id: 2, name: 'televisions', departmentId: 2}
  ];
});

和下拉菜单:

<select ng-model="department" ng-options="department.name for department in departments" ng-change="changeDepartment()">
  <option value="">Department</option>
</select>

<select ng-model="category" ng-options="category.name for category in categories" ng-change="changeCategory()">
  <option value="">Category</option>
</select>

我希望部门下拉菜单显示所有这三个项目,但仅限于“干货”#39;和&#39;电子&#39;应该是可选择的,因为类别中的项目通过departmentId属性映射到Department。冷冻食品应该是灰色的。

Plunker:http://plnkr.co/edit/c7rZ05qqRCnB7L0ANgZ4?p=preview

提前致谢。

1 个答案:

答案 0 :(得分:1)

只需使用第二个select中的$filter 'filter',即可:

  <select ng-model="category" ng-options="category.name for category in categories|filter:{departmentId:department.id}" ng-change="changeCategory()">
    <option value="">Category</option>
  </select>

Example

更新

由于ng-options没有提供指示应禁用哪些值的功能,因此您只有2个选项:

  1. 创建一个自定义指令,为您提供该选项,这不是一件容易的事,因为该指令应该关注ng-select的集合以及其他选择的集合或选定值,换句话说:ng-options with disabled rows不会为你工作。

  2. 使用ng-repeat构建您的选择,更容易,如下所示:

  3.    <div ng-controller='MainCtrl'>
        <div class="btn-group">
          <select ng-model="departmentID" ng-change="changeDepartment()">
                <option value="">Category</option>
                <option ng-repeat="department in departments" value="{{department.id}}" ng-disabled="(categories|filter:{departmentId:department.id}).length==0">{{department.name}}</option>
          </select>
        </div>
        <div class="btn-group">
          <select ng-model="categoryID" ng-change="changeCategory()">
                <option value="">Category</option>
                <option ng-repeat="category in categories" value="{{category.id}}" ng-disabled="departmentID!=category.departmentId">{{category.name}}</option>
          </select>
        </div>
       </div>
    

    Example