2

I have an object like so:

$scope.properties = {
    1: 'Option A',
    2: 'Option B',
    3: 'Option C'
};

And an ng-model variable like so:

$scope.selectedValue = 2;

And some markup like so:

<select ng-options="key as value for (key, value) in ctl.properties" 
        ng-model="ctl.selectedValue">
</select>

But there seems to be absolutely no way of pre-selecting a value from that dropdown by its value. I've managed to get it to work if I set the selected value like this:

$scope.selectedValue = 'Option B';

How on earth do I get the <select> to pre-select using the option value (the key of the object) not the actual option text.

Please note, I'm not using an array of objects like mostly every article I've found uses. I've just got an object. I also don't want to change it to an array of objects. There must be a way to do this.

Many Thanks.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
simon_www
  • 489
  • 2
  • 5
  • 13

1 Answers1

2

The dropdown needs a string key instead of a numeric one:

$scope.selectedValue = '2';

Here is a codepen as an example.

M0nst3R
  • 5,186
  • 1
  • 23
  • 36
  • Thank you so much , I was so fixated on getting it working with the value, that I didn't think to retrieve the text using the value. – simon_www Oct 18 '17 at 12:06
  • My pleasure, glad I could help. – M0nst3R Oct 18 '17 at 12:07
  • Okay so there's a slight problem with this, in that if the selectedValue is the string, when you then change the dropdown, the ng-model will overwrite the string with the actual value. So "Option C" if chosen sets the ng-model to "3" and that in turn would change the text of the option to "3" – simon_www Oct 18 '17 at 13:53
  • I suspect something weird is happening in your controller, what version of AngularJS are you using ? Also take a look at this [codepen](https://codepen.io/glouhaichi/pen/wrRNJq) where you only need to select the key of the object for `ng-model` to work. – M0nst3R Oct 18 '17 at 14:13
  • Okay, thank you. So I went back to using just the raw value, and it didn't work immediately, then I realised that `selectedValue = 2;` is different to `selectedValue = '2';`. Turns out that was causing an issue too! – simon_www Oct 18 '17 at 15:08
  • 1
    Yes, it is, I will change my answer to reflect the right answer now. – M0nst3R Oct 18 '17 at 15:09