ccostel
ccostel

Reputation: 117

Select ng-options group names are not updating | Dynamic ng-options groups

I have a dropdown select with grouped ng-options. The user should be able to dynamically change the naming of the group name in an input field. On change of the group name value the select directive is not being updated unless you make a new selection.

Anybody had the same kind of problem?

Here's the jsbin: http://jsbin.com/ziyeduzalo/edit?html,js,output

This is how my code looks: .js

$scope.players = [
  {name: 'Gene', team: 'alpha'},
  {name: 'George', team: 'beta'},

];


$scope.change = function() {
  $scope.players[0].team = 'new-group-name';
};

.html

<select ng-options="player.name group by player.team for player in players " ng-model="systemType.tertiaryEquipment"></select>

UPDATE: This seem to work in older versions of angular then 1.4.x.

Upvotes: 0

Views: 725

Answers (2)

Jose Rocha
Jose Rocha

Reputation: 1115

For others that may come to this problem the resolution for this particular problem where to use the track by.

Track by should be used to identify the options as unique in the select, so there should be diferent approach on if this is the real solution to this.

Since the ng-options group by will generate optgroups we use that in advantage so we can use the track by on the object of the group by. The optgroups will be unique on the display of the select.

So in this case:

<select ng-options="player.name group by player.team for player in players track by player.team" ng-model="systemType.tertiaryEquipment"></select>

jsfiddle

Note: Angular version 1.4.9 used to test this.

Upvotes: 1

Andrew Donovan
Andrew Donovan

Reputation: 552

Here, i've edited a copy of your js bin. Basically i've told angularJS to re-compile the select input, for it to change.

This is done within a controller, which is a BAD PRACTICE, create a custom directive to do such manipulations. And use provided element variable for selecting DOM element select instead of document.querySelector()

http://jsbin.com/miyecireba/1/edit?html,js,output

Upvotes: 1

Related Questions