AngularJS添加空选项以进行选择

时间:2014-11-13 23:34:36

标签: angularjs angularjs-ng-repeat

请看看这个plunker - http://plnkr.co/edit/l0NqQmvKXPXluyv0gYO3?p=preview

我有两个相互依赖的选择。

每当我在第一个下拉列表中选择一个值,然后选择Deployment #1Deployment #2,然后我再次选择组织,angularjs会在第二个下拉列表中添加一个空选项集。我不知道为什么会这样......

以下是我的HTML代码 -

<select ng-model="temp1">
  <option ng-repeat="opt in data.organizations" value="{{opt.id}}">{{opt.name}}</option>
  <option value="">2</option>
                        <option value="">1</option>
                        <option value="">3</option>
</select>
<select ng-model="temp2" ng-disabled="!temp1">
  <option ng-repeat="deployment in data.deployments | filter : { organizationID : temp1}" 
    value="{{deployment.id}}">{{deployment.name}}</option>
  <option value="">4</option>
                        <option value="">5</option>
                        <option value="">6</option>
</select>

以下是我的angularjs代码 -

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

app.controller('MainCtrl', function($scope) {
  $scope.temp1 = '';
  $scope.temp2 = '';
  $scope.data = {"deployments": [{
    "id": "cd22276d-618b-13f4-94ad-0e0c29669958",
    "name": "Deployment #1",
    "organizationID": "gd28276d-668b-11e4-945d-000c29609978",
    "roleID": "cd1dbddf-668b-11e4-945d-000c29609978"
  }, {
    "id": "cd22276d-668b-11f4-94ad-0e0c29609928",
    "name": "Deployment #2",
    "organizationID": "cd28276d-668b-11e4-945d-000c29609928",
    "roleID": "cd1dbddf-668b-11e4-945d-000c29609978"
  }],
  "organizations": [{
    "id": "gd28276d-668b-11e4-945d-000c29609978",
    "name": "Organization 1"
  }, {
    "id": "cd28276d-668b-11e4-945d-000c29609928",
    "name": "Organization 2"
  }]};  
});

1 个答案:

答案 0 :(得分:0)

这是因为当您切换回temp2 === "Deployment #1"时,由于过滤,这不是一个有效的选项,因此Angular会添加一个空的,这样您就不会意外地覆盖ViewModel - 在这种情况下temp2

您可以修改它,例如,在第一个ng-change="temp2 = undefined"中设置select