Smart Tech for a better Web
Angular.js has a powerful directive waiting for you: it's ng-select. With it you can fill an HTML-select box from your model. It supports a pretty cool selector syntax, which is - unfortunately - a little bit tricky.
Let's assume you have a JSON stream which looks like this:
The good thing is, you have a pretty flat data stream. When I started with this feature, I had an array of groups each containing the specific items. It was not possible for me to fill a select box that way. Instead, I refactored some of my code to what you can see above. Angular.js would take care of the grouping on it's own.
Here is my select definition:
ng-model is the name of the property which will reference the selected option. ng-options is the directive which fills the dropdown. It deserves a bit more attention.
You will understand it more easily if you read it from right to left. First there is:
It means you'll iterate through elements which are stored in myOptions. Every element will become available in this expression with the name "value".
The next part is:
This will tell Angular.js to make up
tags and the label attribute will be filled with the content of the group field.
The last one is:
In this case, value.id will become the model (stored in ng-model), if your users have chosen an option. If you would delete "value.id as", simply the whole value object would become the model.
does exactly what it looks like: it's the label of the select box.
If you run your code, you'll see something like that:
Please look again and check the value attribute of the options. You might have expected it's matching the IDs from your JSON, but that is not the case (and yes, I thought like this initially). Actually this is an increasing number and references the position of the model (which is an array in my case). Don't worry about that - if you select your option the correct ID will be selected and put into your model. Or, if you leave out the value.id part of the expression, the whole selected object will become your model.
You can easily test it.
ng-change will fire if the user has chosen something. You can output it by typing:
I find the syntax of ng-options pretty much counter intuitive. It took me a good while to understand it and I was glad about the nice help on the AngularJS mailinglist. That said, I think more examples on the docs and an improved syntax would really help. Like:
Here is a working JS fiddle example which illustrates the use of the ng-select directive: http://jsfiddle.net/jm6of9bu/2/