使用ng-options的ng-repeat内的默认选择下拉列表

时间:2018-03-07 07:48:30

标签: javascript html angularjs angularjs-ng-repeat ng-options

我无法弄清楚如何将默认选择设置为Extras字段。 Main和Extras的选择选项相同,但默认值应设置如下:[0]进入Main,从[1]直到列表末尾为Extras。有关如何实现这一目标的任何建议吗?

结构是这样的:

 <div>Main selection</div>
  <input type="text" ng-model="mainInput" />
  <select data-ng-options="option.id as option.title for option in items" ng-model="mainSelection" ng-init="mainSelection = mainSelection"></select>

  <div>Extras</div>
  <div ng-repeat="i in extraSelections">
    <input type="text" ng-model="extraInput" />
    <select data-ng-options="option.id as option.title for option in items" ng-model="extraSelection"></select>
  </div>

 $scope.extraSelections = [];
  $scope.items = [{
      'id': 1,
      'title': 'Main/Extra'
    },
    {
      'id': 2,
      'title': 'Extra/Main1'
    },
    {
      'id': 3,
      'title': 'Extra/Main2'
    },
    {
      'id': 4,
      'title': 'Extra/Main3'
    }
  ];

  function getExtraSelections() {
    if ($scope.items) {
      for (var i = 1; i < $scope.items.length; i++) {
        var rowObj = {
          input: null,
          title: null
        };
        $scope.extraSelections.push(rowObj);
      }
    }
  }

  function setDefaultSelections() {
    $scope.mainSelection = $scope.items[0].id;
  }

Plunker:     https://plnkr.co/edit/Yw94hLx3ntyOFL7AFmkx?p=preview

编辑: 我尝试使用ng-init或ng-selected传递模型和索引,如下所示:

$scope.getDefExtra = function(model, index){
  model = $scope.items[index+1].id;
  return model;
}

该函数获取并设置正确的值,但视图中没有变化。

2 个答案:

答案 0 :(得分:0)

请更改此

$scope.mainSelection = $scope.items[0];

$scope.mainSelection = $scope.items[0].id;

setDefaultSelections()$scope.items initialization之后调用。

答案 1 :(得分:0)

搞定了。 答案很简单:

 <select data-ng-options="option.id as option.title for option in items" ng-model="extraSelection" ng-init="extraSelection = setExtraDefault(extraSelection,$index)"></select>

$scope.setExtraDefault = function(model, index){
    model = $scope.items[index+1].id;
    return model;
  }