2 ng-option,2nd ng-option的条件选项

时间:2016-08-26 02:24:00

标签: angularjs

所以我想要做的就是相当简单。我对ng-options很新。我一直在使用ng-repeat,在关于ng-options的黑暗中,但我相当肯定ng-options会更好地完成我的任务。

我要做的是根据第一个ng-options中选择的内容,确定用户在第二个ng-options中看到的内容。

这是我的HTML,我最好的尝试我想做的事情:

<div class="formRow">
    <select name="Client" ng-model="selectedClient" ng-options="x.Name for x in clients">
    </select>
</div>
<div class="formRow">
    <select name="Profile" ng-options="x.Name for x in profiles" ng-if="x.ID = selectedClient">
    </select>
</div>

你可以想象,我有两个对象:

$scope.clients = [{
  Name:"ClientA",
  ID:"1"
},{
  Name:"ClientB",
  ID:"2"
}];

$scope.profiles = [{
  Name:"NORTH",
  ID:"1",
  ClientID:"1"
},{
  Name:"SOUTH",
  ID:"2",
  ClientID:"1"
},{
  Name:"EAST",
  ID:"3",
  ClientID:"2"
},{
  Name:"WEST",
  ID:"4",
  ClientID:"2"
}];

因此,在我的HTML中,使用ng-options,我真正想要逻辑地做的是,我希望第二个ng-options中显示的配置文件只是其配置文件。 ClientID等于所选第一个ng-options的clients.ID

我现在没有遇到任何错误。但是使用该HTML,只会填充客户端选项。

我希望这是有道理的。谢谢!

1 个答案:

答案 0 :(得分:2)

您正在寻找的是级联下拉列表。

BTW使用ng-options指令你也需要使用ng-model指令。

您可以在ng-options指令中使用名为 filter 的AngularJS中的内置过滤器,根据客户端过滤掉配置文件。

请参阅下面的示例代码段。

angular
  .module('demo', [])
  .controller('DefaultController', DefaultController);
  
  function DefaultController() {
    var vm = this;
    vm.clients = [
    { name: "ClientA", id: "1" },
    { name: "ClientB", id: "2" }
    ];

    vm.profiles = [
    { name: "NORTH", id: "1", clientId: "1" },
    { name: "SOUTH", id: "2", clientId: "1" },
    { name: "EAST", id: "3", clientId: "2" },
    { name: "WEST", id: "4", clientId: "2" }
    ];
  }
  
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
  <div ng-controller="DefaultController as ctrl">
    <div class="formRow">
      <select name="Client" ng-model="ctrl.selectedClient" ng-options="x.name for x in ctrl.clients">
      </select>
    </div>
    <div class="formRow">
      <select name="Profile" ng-model="ctrl.selectedProfile" ng-options="x.name for x in ctrl.profiles | filter: { clientId: ctrl.selectedClient.id }">
      </select>
    </div>
  </div>
</div>

相关问题