在Angular

时间:2016-04-11 16:45:15

标签: angularjs drop-down-menu default angular-ngmodel ng-options

我有两个下拉菜单,一个依赖于另一个。我最初使用ng-repeat获得了我的代码,但是读到使用ng-options更有效。但是,在切换时,我不能再使用ng-selected作为默认值。

我已经研究了在ng-options中设置默认选项的不同方法,但是他们使用<option value="">Select Something Here</option>作为自定义选项或直接从数据集中选择。但是,我的价值将会改变。

这是一个使用ng-repeat的工作plunker:

http://plnkr.co/edit/Ie4VDDlrwSUSqIq7laoa?p=preview

以下是使用ng-option缺少默认值的plunker:

http://plnkr.co/edit/TGoWTMqOuJnWKNTUARWI?p=preview

默认值应该是$scope.defnum,它来自与我的下拉列表中的值不同的数据集,因此我希望使用默认的DefCom = defnum。我已尝试通过在控制器中分配原始变量使用ng-init来执行此操作:

 $scope.defcom = 4;
 var original_defcom = $scope.defcom;

并在模板中使用ng-init="original_defcom"

并在ng-model中,甚至将其包装在<option>标记

2 个答案:

答案 0 :(得分:1)

在ng-options

中执行此操作
<select ng-model="defcom"
    ng-options="opt.DefCom as opt.DefCom for opt in acct_info | filter:{Req:'MUST'}:true" >
</select>

然后,您必须更改de $ scope.defcom类型以匹配该数组。在plunker中,变量是一个数字,数组中充满了字符串。你必须改变其中一个。如果我在哪里,我会更改数组中对象的属性类型。 ng-options自动解析数字。

这是你的一个版本的plunker经过一些改变:

http://plnkr.co/edit/tIeDEC8MxfcvnRrc0Njh?p=preview

答案 1 :(得分:1)

尝试这样。

并更改为:$scope.defcom = "4";

 <select ng-model="defcom" ng-options="opt.DefCom as opt.DefCom for opt in acct_info | filter:{Req:'MUST'}:true" >>

&#13;
&#13;
// Code goes here

angular.module("app", [])
  .controller("MainCtrl", function($scope) {
    $scope.test = "This is a test";
    $scope.defcom = "4";
    var original_defcom = $scope.defcom;
    var original_com = $scope.com;
    
    $scope.acct_info = [
      {
        "Req": "MUST",
        "DefCom": "1"
      },
      {
        "Req": "NoMUST",
        "DefCom": "5"
      },
      {
        "Req": "MUST",
        "DefCom": "4"
      },
      {
        "Req": "MUST",
        "DefCom": "7"
      }
    ];
    
    $scope.cust_info = [
      {
        "Customer": "1",
        "Com": "1"
      },
      {
        "Customer": "2",
        "Com": "1"
      },
      {
        "Customer": "3",
        "Com": "4"
      },
      {
        "Customer": "4",
        "Com": "4"
      },
      {
        "Customer": "5",
        "Com": "7"
      },
      {
        "Customer": "6",
        "Com": "7"
      },
      {
        "Customer": "7",
        "Com": "7"
      }
    ];
  });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
    <h1>Hello Plunker!</h1>
    <div ng-controller="MainCtrl">
      <p>{{ test }}</p>
      <select ng-model="defcom" ng-options="opt.DefCom as opt.DefCom for opt in acct_info | filter:{Req:'MUST'}:true" >>
  </select>
  
    </div>
  </div>
&#13;
&#13;
&#13;

`