How to add option at first position in ng-options

时间:2016-10-20 13:03:49

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

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?

4 个答案:

答案 0 :(得分:0)

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>

答案 1 :(得分:0)

add the option in the controller after fetching items,

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

updated code

答案 2 :(得分:0)

更改您的选择,如下所示

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

答案 3 :(得分:0)

我们可以将 ng-selected =&#34;期望的项目值&#34;属性选择它的元素。

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