Search code examples
angularjsselectangularjs-track-by

angular select 'track by' resets selected


I'm struggling getting "selected" to work with 'track by' for Angular select element. I have the following select:

    <select id="licenseType" ng-model="selectedLicense" 
            ng-options="key for (key, value) in licenseMap track by key" 
            ng-change="doUpdate()">
    </select> 

with this js:

$scope.selectedLicense = $scope.licenseMap["Please Select"];

The above js works when I get rid of 'track by key' - the initial selection gets preset. With 'track by key' in place the pre-selection is a blank. I need 'track by key' in place to get hold of selected value, it is the only thing that worked so far. I have tried teh following combination so far that did not work:

/*
var license = document.getElementById('licenseType');
license.options.selectedIndex = 1;
license.options[license.options.selectedIndex].selected = true;
$("#licenseType").val("Please Select");
$('#licenseType').children('option[value="1"]').attr('selected', true);     
*/

I will most appreciate some help here getting it to work. Thank you.


Solution

  • do something like this: http://codepen.io/alex06/pen/XjarJd

    div(data-ng-app="app")
     div(ng-controller="appController")
       select.form-control(ng-model="selectedItem", ng-options="option.value as option.name for option in typeOptions track by option.value" ng-init="selectedItem=typeOptions[0]")
    
    
    (function(){
      'use strict'
      angular
        .module('app', [])
        .controller('appController', ['$scope', function($scope){
    
          $scope.typeOptions = [
            { name: 'Feature', value: 'feature' }, 
            { name: 'Bug', value: 'bug' }, 
            { name: 'Enhancement', value: 'enhancement' }
           ];
        }])
    })()
    

    The example is made in jade, but it's almost the same syntax.By the way, if you still want to work with an object instead of array you can also do this:

    <!DOCTYPE html>
    <html ng-app="app">
    
    <head>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js">              </script>
      <link rel="stylesheet" href="style.css" />
      <script type="text/javascript">
        angular.module('app', [])
          .controller('IndexCtrl', ['$scope', function($scope) {
            $scope.types = {
              1: "value1",
              2: "value2",
              5: "value3"
            };
          }]);
        </script>
      </head>
      <body ng-app="app" ng-controller="IndexCtrl">
        <select ng-model="type" ng-options="k as v for (k, v) in types">
          <option value="">Please select</option>
        </select>
      </body>
    
    </html>