Michael
Michael

Reputation: 13616

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?

Upvotes: 0

Views: 3596

Answers (4)

Palani Kumar
Palani Kumar

Reputation: 350

We can just put ng-selected ="desirable item value" attribute to select element that is it.

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

Upvotes: 0

user7046991
user7046991

Reputation:

change your select like below

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

Upvotes: 0

Mohit Tanwani
Mohit Tanwani

Reputation: 6628

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="[email protected]" 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>

Upvotes: 0

prasanna
prasanna

Reputation: 14

add the option in the controller after fetching items,

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

updated code

Upvotes: 0

Related Questions