【问题标题】:How to add option at first position in ng-options如何在 ng-options 的第一个位置添加选项
【发布时间】:2023-06-05 04:50:01
【问题描述】:

我的页面中有ng-option 元素。

它在模板中的外观:

<select ng-model="selectedItem" ng-options="item.name for item in items track by item.id"></select>

在控制器中:

 $scope.selectedItem = {};

 $scope.items = [{name: 'one', id: 30 },{ name: 'two', id: 27 },{ name: 'threex', id: 50 }];

在我的项目中,我从一些查找表中获取范围项。

我需要添加到 ng-select 这个元素的值 -1:

<option value="-1">- manual -</option>

看起来像这样:

<select ng-model="selectedItem" ng-options="item.name for item in items track by item.id">
   <option value="-1">- manual -</option>
</select>

这里是Plunker

但我没有看到 manual 选项。

知道为什么我在视图中看不到手动选项吗?

【问题讨论】:

    标签: angularjs angular-ngmodel ng-options angularjs-ng-options angularjs-select


    【解决方案1】:

    由于您使用 id-name 对反对,您需要使用 unshift 在第一个位置添加一个新选项。

    $scope.items.unshift({name: 'manual', id:-1});
    

    然后指定默认选择的选项。

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

    var app = angular.module('plunker', []);
    
    app.controller('MainCtrl', function($scope) {
      
      $scope.items = [];
      $scope.items = [{name: 'one', id: 30 },{ name: 'two', id: 27 },{ name: 'threex', id: 50 }];
      
      $scope.items.unshift({name: 'manual', id:-1});
      $scope.selectedItem = $scope.items[0];
    });
    <!DOCTYPE html>
    <html ng-app="plunker">
    
      <head>
        <meta charset="utf-8" />
        <title>AngularJS Plunker</title>
        <script data-require="angular.js@1.3.15" data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js"></script>
        <script>document.write('<base href="' + document.location + '" />');</script>
        <link rel="stylesheet" href="style.css" />
        <script src="app.js"></script>
      </head>
    
      <body ng-controller="MainCtrl">
        <select ng-model="selectedItem" ng-options="item.name for item in items track by item.id">
          
        </select>
        
      </body>
    
    </html>

    【讨论】:

    • 我在选项中需要这个值
    【解决方案2】:

    在获取项目后在控制器中添加选项,

    $scope.items.push({name:'-manual-', id: -1});
    

    updated code

    【讨论】:

      【解决方案3】:

      如下所示更改您的选择

      <select ng-model="selectedItem" ng-options="item.name for item in items track by item.id">
         <option value="">Manual</option>
          </select>
      

      【讨论】:

        【解决方案4】:

        我们可以把 ng-selected ="desirable item value" 属性放到选择元素上。

        <select ng-model="selectedItem" ng-options="item.name for item in items track by item.id" ng-selected="50">
         <option value="">Manual</option>
        </select>
        

        【讨论】: