【问题标题】:add default option to angularjs select将默认选项添加到 angularjs 选择
【发布时间】:2016-03-29 13:51:34
【问题描述】:

我正在尝试为带有角度的选择添加一个默认选项,但它添加了一个空白选项,当我选择它时它奇怪地消失了。

我正在使用ng-options 将对象绑定到选择,就像这样。我正在附加这样的默认选项:

var DocumentSearchController = function (documentsService) {
    documentsService.getDocTypes().then(function (results) {
        this.documentTypes = results.data;
        this.documentTypes.unshift({ DocumentTypeID: null, Name: 'Select a Document Type' });
    }.bind(this));

对象的结构是:

[{DocumentTypeID: 1, Name: 'Blah'}]

然后我使用ng-options 绑定对象:

<select class="form-control"
        id="documentTypeSelector"
        name="documentTypeSelector"
        ng-model="vm.selectedDocumentType"
        ng-options="option.Name for option in vm.documentTypes | orderBy: 'option.DocumentTypeID':false track by option.DocumentTypeID">
</select>

然后令人讨厌的是,奇怪地添加了一个空白选项,当我选择一个项目时该选项被删除。

这些选项也没有排序,所以我怀疑我的列表理解是错误的。

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    要定义默认的&lt;select&gt; 元素,只需为ng-model 绑定变量分配一个&lt;option&gt; 元素(或值)中可用的默认值。

    在您的情况下,vm.selectedDocumentType 应设置为 vm.documentTypes[theIndexYouChoose].DocumentTypeID

    一般来说,一个简化的例子可以是

    // given $scope.options = [1, 2, 3];
    <select ng-init="selectedOption=1" ng-option="option for option in options" ng-model='selectedOption'>
    </select>
    

    你会发现没有空选项,选择的选项将是 1

    【讨论】:

      【解决方案2】:

      您可以通过这种方式添加默认值:

      <select class="form-control"
              id="documentTypeSelector"
              name="documentTypeSelector"
              ng-model="vm.selectedDocumentType"
              ng-options="option.Name for option in vm.documentTypes | orderBy: 'option.DocumentTypeID':false track by option.DocumentTypeID">
          <option value="">Select a Document Type</option>
      </select>
      

      编辑或使用init函数

      <select class="form-control"
              ng-init="vm.selectedDocumentType= vm.documentTypes[0]" 
              id="documentTypeSelector"
              name="documentTypeSelector"
              ng-model="vm.selectedDocumentType"
              ng-options="option.Name for option in vm.documentTypes | orderBy:'option.DocumentTypeID':false track by option.DocumentTypeID">
      </select>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-23
        • 1970-01-01
        • 2016-04-15
        • 1970-01-01
        • 2022-07-26
        • 2014-07-26
        • 2016-12-11
        • 1970-01-01
        相关资源
        最近更新 更多