【问题标题】:Default selections inside ng-repeat with ng-options drop downng-repeat 中的默认选择与 ng-options 下拉
【发布时间】:2018-03-07 16:49:40
【问题描述】:

我不知道如何将默认选择设置到附加字段中。 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;
}

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

【问题讨论】:

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


    【解决方案1】:

    搞定了。 答案很简单:

     <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;
      }
    

    【讨论】:

      【解决方案2】:

      请改一下

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

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

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

      【讨论】:

      • 感谢您的回答。我用 Main 进行了编辑。但是额外的选择呢?这是我的主要问题。
      猜你喜欢
      • 2014-07-04
      • 1970-01-01
      • 2018-03-21
      • 2023-04-09
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      • 2016-08-01
      • 2014-07-26
      相关资源
      最近更新 更多