This is the first of many posts to come that may help you understand how to use AngularJS libraries and syntax. This is a work in progress, part of the purpose of this blog is for me to document what I learn, share and hopefully help you out.
ngOptions allows you to create a select form drop down with some convenience, so I am going to try and summarize the Angular documentation into layman’s terms. Sure you can use ng-repeat as well, but this convenient alternative allows you to choose a default selection.
So first, the example:
<select ng-options="myObject.name for myObject in myObjects track by myObject.id" ng-model="myObjectSelection"> </select>
So this somewhat un-intuitive syntax can be broken down as follows.
Let’s first assume our form is bound to a controller using the ng-controller syntax. Our goal is to display a list of values returned from the controller/service and display the values in the select/option drop down. Our controller may hard code data or get it from a database, but either way, let’s assume we get at least 1 result back (we won’t get into details if no results are returned).
Using our example above, our controller will end up returning an array of values called myObjects (yes plural). Inside of the collection of the JSON objects are individual objects (maybe called myObject, oh so creative) with fields such as id and name (we’ll keep is simple).
The ng-options syntax starts with the object attribute that will display visible to the user in the select/option. So in our case, the name attribute of the myObject object would be displayed.
The for in assigns myObject as the variable name in the expression where myObjects is what we passed over in the $scope. The track by syntax is what does the magic to compare the current item in the list during the loop to something that we assign in the controller via the $scope. Ok hold on, what did I just say there?? We forgot one key step, our controller must set the value of myObjectSelection as shown in the ng-model on the $scope. Now the real sneaky part here is, you must not assign the myObjectSelection to the id field (the field you think that would be compared), it’s actually the object instance that is assigned. Angular does the magic work to use the track by syntax to use some form of reflection on the myObjectSelection “object” (in other words, internally, Angular will do the compare). If you set $scope.myObjectSelection = myObject.id, things won’t work, it must be $scope.myObjectSelection = myObject;