Working with Select Using Angularjs's Ng-Options

Select default option with ng-options using a flat array

How to select the hard-coded null option with ng-options and ng-model

To select the single hard-coded <option>, assign null to the model:

angular.module('MyApp', []).controller('MyCtrl', ['$scope', function ($scope) {
$scope.testOpt = [
'ID',
'Name',
'Email',
'Address'
];
̶$̶s̶c̶o̶p̶e̶.̶r̶e̶s̶u̶l̶t̶O̶p̶t̶ ̶=̶ ̶'̶'̶;̶
$scope.resultOpt = null;
}]);

From the Docs:

Optionally, a single hard-coded <option> element, with the value set to an empty string, can be nested into the <select> element. This element will then represent the null or "not selected" option.

For more information, see

  • AngularJS <select> Directive API Reference

The DEMO

angular.module('MyApp', [])
.controller('MyCtrl', ['$scope', function ($scope) {

$scope.testOpt = [
'ID',
'Name',
'Email',
'Address'
];
$scope.resultOpt = null;
}]);
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="MyApp" ng-controller="MyCtrl">

<select ng-options="opt as opt for opt in testOpt"
data-ng-model="resultOpt">
<option value="">Choose Category</option>
</select>

<br><br>
<button ng-click="resultOpt=null">Reset</button>

</body>

Working with select using AngularJS's ng-options

One thing to note is that ngModel is required for ngOptions to work... note the ng-model="blah" which is saying "set $scope.blah to the selected value".

Try this:

<select ng-model="blah" ng-options="item.ID as item.Title for item in items"></select>

Here's more from AngularJS's documentation (if you haven't seen it):

for array data sources:

  • label for value in array
  • select as label for value in array
  • label group by group for value in array
    = select as label group by group for value in array

for object data sources:

  • label for (key , value) in object
  • select as label for (key , value) in object
  • label group by group for (key, value) in object
  • select as label group by group for (key, value) in object

For some clarification on option tag values in AngularJS:

When you use ng-options, the values of option tags written out by ng-options will always be the index of the array item the option tag relates to. This is because AngularJS actually allows you to select entire objects with select controls, and not just primitive types. For example:

app.controller('MainCtrl', function($scope) {
$scope.items = [
{ id: 1, name: 'foo' },
{ id: 2, name: 'bar' },
{ id: 3, name: 'blah' }
];
});
<div ng-controller="MainCtrl">
<select ng-model="selectedItem" ng-options="item as item.name for item in items"></select>
<pre>{{selectedItem | json}}</pre>
</div>

The above will allow you to select an entire object into $scope.selectedItem directly. The point is, with AngularJS, you don't need to worry about what's in your option tag. Let AngularJS handle that; you should only care about what's in your model in your scope.

Here is a plunker demonstrating the behavior above, and showing the HTML written out


Dealing with the default option:

There are a few things I've failed to mention above relating to the default option.

Selecting the first option and removing the empty option:

You can do this by adding a simple ng-init that sets the model (from ng-model) to the first element in the items your repeating in ng-options:

<select ng-init="foo = foo || items[0]" ng-model="foo" ng-options="item as item.name for item in items"></select>

Note: This could get a little crazy if foo happens to be initialized properly to something "falsy". In that case, you'll want to handle the initialization of foo in your controller, most likely.

Customizing the default option:

This is a little different; here all you need to do is add an option tag as a child of your select, with an empty value attribute, then customize its inner text:

<select ng-model="foo" ng-options="item as item.name for item in items">
<option value="">Nothing selected</option>
</select>

Note: In this case the "empty" option will stay there even after you select a different option. This isn't the case for the default behavior of selects under AngularJS.

A customized default option that hides after a selection is made:

If you wanted your customized default option to go away after you select a value, you can add an ng-hide attribute to your default option:

<select ng-model="foo" ng-options="item as item.name for item in items">
<option value="" ng-if="foo">Select something to remove me.</option>
</select>

AngularJS dynamic select within ng-repeat using ng-options - set default selected option

Try below, it should work:

<select ng-model="currentSelectedProperty.Name" ng-init="currentSelectedProperty.Name=data.sortInfo.availableProperties[0]" ng-options="item as item.PropertyDisplayName for item in data.sortInfo.availableProperties track by item.PropertyName">

Why Angular ng-options with 'track by' can't selected by id

As explained in this github issue - "ng-options track by and select as are not compatible" and shown in this fiddle

"you just can't combine value as label for collection with track by. You have to pick the one or the other.".

For your case, the select should be:

<select ng-model="country" ng-options="country as country.name for country in countryList track by country.id"></select>

and in JS

$scope.country = $scope.countryList[0];

JSFiddle here for your case.

The value selected will be the object and not just the id alone.

Again the point is, you have to chose between select as label or the track by case.

AngularJS ng-options ng-model option selected by id

Udpated the ng-options to

ng-options="item.id as item.title for item in countries">

Answer

without track By - JSFiddle

with track By - JSFiddle

track by just helps Angular internally with array sorting as far as I know. The value of the options is defined by the first argument (in your case item). If you want it to be by id then you should use item.id as item.name for item in items

AngularJs - ng-options object.object

Click this Demo example

Html Code for reference:

 <html ng-app="myapp">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link href="style.css" rel="stylesheet" />
<script data-semver="1.5.8" src="https://code.angularjs.org/1.5.8/angular.js" data-require="angular.js@1.5.x"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<select ng-model="country" data-ng-options="country for country in countries" ng-change="countryChange()">
<option value="">Select country</option>
</select>
<br>
<select ng-model="state" ng-options="state for state in allStates">
<option value="">Select state</option>
</select>
<br>
Country: {{country}}
<br>
State: {{state}}
</body>
</html>

JS code for reference:

var app = angular.module('myapp', []);

app.controller('MainCtrl', function($scope) {
$scope.countries = ["USA","Canada"];
$scope.states = [{
"name": "Alabama",
"countryId": "USA"
}, {
"name": "Alaska",
"countryId": "USA"
}, {
"name": "Arizona",
"countryId": "USA"
}, {
"name": "Alberta",
"countryId": "Canada"
}, {
"name": "British columbia",
"countryId": "Canada"
}];

$scope.countryChange = function(){
$scope.allStates = [];
angular.forEach($scope.states, function(value){
if($scope.country == value.countryId){
$scope.allStates.push(value.name);
}
});
}
});

How to filter a Select with ng-options

You had angular filter on wrong place. Filter should be applied over a players collection, it should not be at the end.

Markup

<select id="players" ng-model="selectedPlayer" 
ng-options="player.name for player in players | filter:{live:'true'} track by player.$id">
<option value="">Select player</option>
</select>

AngularJS ng-options, working with key value pairs in select

You're using $scope.data.myModel as your model and the source element for your options. These should be separate:

$scope.data = {};
$scope.data.myModel = '';
$http.get(baseUrl + "/Lookup/Get?param=Ref_myModel").success(function (result) {

$scope.data.options = result

})
.error(function (error) {
$scope.data.error = error;
});

Then in your view:

<select class="form-control" id="MonStatus"
ng-model="data.myModel"
ng-options="key as value for (key , value) in data.options"></select>

This will bind the selection to myModel and let the options remain what they were...

Some extra advice:

Also, don't do $http calls in your controllers, place them in a service. Always avoid logic as much as possible in your controllers and let services/factories take care of the heavy lifting. Also, it's a pretty good idea to place data- before ng-* attributes.



Related Topics



Leave a reply



Submit