angularjsangular-ngmodelng-optionsangularjs-ng-optionsangularjs-select

How to add option at first position in ng-options


I ng-option element in my page.

Here how it looks in template:

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

In controller:

 $scope.selectedItem = {};

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

In my project I get scope items from some lookup table.

I need to add to ng-select this element with value -1:

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

And it looks like that:

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

Here is Plunker.

But I don't see in view manual option.

Any idea why I cant see manual option in the view?


Solution

  • As you've object with id-name pair, you need to use unshift to add a new option at first position.

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

    Then specify the option to be selected by default.

    $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>