var app = angular.module('myApp', []); app.controller('MainCtrl', function($scope) { $scope.selectAction = function() { }; $scope.items = [ { id: 1, g:'a', name: 'foo' }, { id: 2, g:'a', name: 'bar' }, { id: 3, g:'a', name: 'blah' }, { id: 1, g:'b', name: 'foo' }, { id: 2, g:'b', name: 'bar' }, { id: 3, g:'b', name: 'blah' } ]; }); app.directive( 'selectLatest', function() { function fixSelectedIndex(elem){ console.log('fix'); console.log(elem[0]); var selectedText = !!elem[0].selectedOptions ? elem[0].selectedOptions[0].text : elem[0].options[elem[0].selectedIndex].text, optionsLength = elem[0].options.length, i = 0, candidate; for(i=0; i<optionsLength;i++){ candidate = elem[0].options[i].text; console.log('candidate: ' + candidate); if(selectedText === candidate){ elem[0].selectedIndex = i; return; } } } return { // restrict to an attribute type. restrict: 'A', // element must have ng-model attribute. require: 'ngModel', // scope = the parent scope // elem = the element the directive is on // attr = a dictionary of attributes on the element // ctrl = the controller for ngModel. link: function(scope, elem, attr, ctrl) { console.log('link'); elem.bind( 'blur', function(){fixSelectedIndex(elem);} ); elem.bind( 'click', function(){fixSelectedIndex(elem);} ); } }; } );
<h1>Same same, but different</h1> <p>Selected index of duplicated items in form select elements</p> <h2>Repro</h2> <p>select a value from the first option group. Double check the selection is in the first option group:</p> <div ng-app="myApp"> <div ng-controller="MainCtrl"> <label for="select1">Without fix</label> <br/> <select id="select1" ng-model="selectedItem2" ng-change="selectAction()" ng-options="item.id as item.name group by item.g for item in items"> </select> <br/> <label for="select2">With fix:</label> <br/> <select id="select2" ng-model="selectedItem1" ng-change="selectAction()" select-latest="true" ng-options="item.id as item.name group by item.g for item in items"> </select> </div> </div>