I have been doing Angular.JS in production projects for months, that it did surprise me recently how I haven’t used drop-downs in it. Well, I mean how I haven’t used them enough to get into several problems I had in my current project, and other friends at the same office had in their project as well.

To save you the pain I went through, I’ll list some problems and solutions here, and then give you a video that shows going through all of them ans the thought process that led to the solutions.

Initial selection

<select ng-model="myModel.someObject"
    ng-options="someObject.text for someObject in objectList ">
</select>

Assuming someObject in the model has the same properties and values as someObject in the objectList, it will still not be selected.

It’ll only be selected if someObject was actually one of the objects in objectList, like objectList[0] or whatever. Otherwise, Angular.JS will insert an empty option tag with no value or text and select that.

Root Cause

Angular.JS uses native JavaScript comparison for comparing the objects. In JavaScript, unrelated to Angular.JS or anything, comparing objects (object literals) is “by reference”, so it doesn’t factor the similarity of the objects. Only checks if the two references compared point to the same object in memory or not.

Solution

An un-documented (AFAIK) feature in ng-options is that you can use some bits from the ng-repeat directive with it, like track by. This allows us to choose some property as the comparison key.

<select ng-model="myModel.someObject"
    ng-options="someObject.text for someObject in objectList track by someObject.key">
</select>

If the key property is a simple type, like Number or string, JavaScript will consider it equal to any other object that has the same value, so we don’t have to use the same objects.

Invalid Value Sent On Server-Side Submit

When Angular.JS writes the <option> tags from an ng-options directive pointing to an array, the value of the option is always the index of the element it maps to in the array. This is not important if you process the selection on client side because you only deal with the result of ng-model anyway, you can use this later to create an AJAX request or whatever.

However, if you intend to submit the form using a normal server submission, and only use Angular.JS for say validation or managing complex form interaction (client-side tables containing sub-items with add/remove/sort for example), this may be a road blocker to using Angular.

Root Cause

By default Angular.JS uses the index of the array to track which object maps to which <option> element.

Solution

Similar to the previous problem, use the track by syntax. Angular.JS will use the track by property value as the <option>‘s value. Most of the time your tracked property is the key property you want to send to the server anyway, so, this should be good enough.

Simple Properties Scenario When Combined With Server-Side Submit

Let’s say you want something as simple as this:

<select
    ng-model="person.genderId"
    ng-options="gender.id as gender.text for gender in genders">
</select>

This syntax will work very well, if you only use this value from JavaScript, you are all set. But if you plan to send it directly to the server (a normal non-AJAX form submit), you’ll want to consider using the track by syntax, like track by gender.id.

However, if you do this, you’ll notice that the select is no longer usable. No initial selection, and changing selection although updates the model, it does not show the new selected value.

Root Cause

The track by syntax expects an object, with the property you use to track. It does not honor the key part used in the key as text syntax (which in our example is g.id as g.text), so, it wants the ng-model to point to an object with the tracked property, it cannot be the key itself directly.

Workaround

I didn’t call this a solution, because it’s pretty much a hack.

<select
    ng-init="person._gender = {id: person.genderId}"
    ng-change="person.genderId = person._gender.id"
    ng-model="person._gender"
    ng-options="gender.id as gender.text
        for gender in genders track by gender.id">
</select>

We created a new property (which I liked to prefix with _ to show it doesn’t normally belong to the model object), initialized it to a new object that contains only our key property id set to the original simple value genderId, and then used that as the model (as in ng-model).

We created and assigned the property in ng-init, then synchronized the changes to the simple property via ng-change. This allows the code everywhere else in the application (like the controller, or other parts of the markup) to only interact with the property we want (genderId in this example), without knowing about our hack. This makes things a bit cleaner, although it still remains a hack rather than a solution.

You can view an example of using this hack here.

Adding extra selection items to the dropdown

One thing you notice if you are affected by the “initial selection” problem, is that the empty <option> tag that Angular.JS adds when it can’t match the ng-model to the array from ng-options disappears when the use changes their selection. We have gone through how to avoid showing the empty option by mistake already.

But if you do want to have that option, it’s easy, just, um, add it!

<select ng-model="myModel.someObject"
    ng-options="someObject.text for someObject in
        objectList track by someObject.key">
    <option value="">-- Select an option--</option>
</select>

The Video

If you want to dig these problems really deep and see what they look like in action, and what was the thought process for solving them like and in some cases other possible solutions, I have put all this in a (rather long) video here:

Now that we're done, click this out ;)

, , , ,
  • Fabian Lopez

    thanks so much that “hack” of yours just saved me a lot of time

  • Aman Jain

    Hi, I had gone through your detailed explanation about the nuances of the select element in Angular JS and also went through the video more than once. It was extremely helpful to understand how the Angular behaves. I have a similar problem with the select but in a bit different scenario :

    In my case, I open a modal window from the main home page, then on the modal window I have a lengthy form to submit in which there are multiple drop-down controls. I tried all possible ways that you had explained in the video, but it just does not seem to be working no matter what I have tried. It’s been more than a day that I am struggling with that and have posted my questions on various other sites but no answers till now. Could you please give me some pointers in my case ? Or if would need the code, then I can paste that here. Please let me know.

  • Pingback: AngularJS-Learning | Nisar Khan

  • Computer Project

    Thanks to your article I solved the annoying problem of the blank option.
    At the moment, I’m stuck on saving the form whit the option selected. Could you take a look at my code? . Thank you. http://plnkr.co/edit/BUDr67xonKZtYAvNQIri

    • http://gurustop.net/ @Meligy

      I think you need to change your ng-init to refer to the item of the list you want by default.
      For example: `ng-init=”anasubject.sbjType = types[0]“`

      Sample plunk http://plnkr.co/edit/MqXNVE2wlZQzYo6Cn94a?p=preview

      • Computer Project

        Thanks a lot that solve my issue. This is my first big project in Angular.js and I very surprised how is it easy to make a CRUD app with few code line(I came from years of Icefaces/Primefaces development).
        However now I’m consider the idea to adopt the angular-kendo-ui in my project.

  • aradul

    Hi, what about ng-options with filter?
    http://plnkr.co/edit/ly99zwupFDqjEXpZiwF7 – blank option again.

  • Laggel

    I literrally love you!! XD Thanks!

  • Pingback: Some notes on <select> and ng-options | angularnotes

  • Jakub

    Meligy,

    Thank you so much for “Initial selection” solution ! I just started using Angular and that blocked me for entire day, I was browsing documentation. blogs, stack overflow and no one gave this advices but you !

  • Rebel Sanders

    I’m new to angularjs and found your article very informative. However, when I tried to apply your techniques, I could not get them to work.

    I posted a question here. http://stackoverflow.com/questions/24463346/i-can-not-get-the-select-working-correctly-in-angularjs/24463786?iemail=1&noredirect=1#24463786

    Here is the newest fiddle http://jsfiddle.net/zeljko/8faa5/15/ Any suggestions? Thanks in advance.

  • vasanth

    what IDE you are using?

  • Noel da Costa

    Have you raised an issue on the angularjs github repository for this? If so please point it out so that we can follow.