Both ngRepeat and ngOptions give you the ability to populate a list of options in a select input. Each has their place and I'm going to demonstrate where you'd use them.
Here’s the model we’ll be working with. All properties have string values.
We have a form that looks like this:
Our controller looks like this:
As you can clearly see, our controller has two arrays, states and counties. The states array is available to the view when it is loaded. The counties array will be updated after a state has been selected.
Now we need to get those Arrays of states and counties into our select inputs so that we have some options to choose from.
You can see that the “State” select field is populated and the correct state is selected based on the contact model. And, because we haven’t populated the counties Array, the “County” select field defaulted to “–Select One–” as expected.
The next thing we need to do is update the counties Array when a state is selected. I’m going to use Angular’s $watch method because I don’t want my view getting cluttered. If you prefer, you could also create a method that executes on controller initialization and also implement ngChange in the view when the user selects a state from the select input. I’m not going to cover the latter method.
Before we can use $watch we’ll need to inject $scope into our controller. And setup the watch inside the controller.
You’ll notice that the “County” options are being populated but they selected value is still the default “–Select One”. This is not what we expected. If you are wondering why this is happening, it’s because ngOptions is not intended to be used when your ngModel is a string property. You also may be wondering, “Hey, we’re using the same approach for ‘states’ and that’s working as expected.” You are right. If the controller has the Array populated with our options before the view is loaded the ngModel will inform ngOptions which item to select. But if we don’t have anything in ngOptions when the view is loaded they will not sync when ngOptions are updated after the initial load.
One side effect that you may notice is that when our selected county (“Multnomah” by default) isn’t available in a state (switch to “Washington”), the selected option will be blank. This is because Angular is hanging on to the value that is in ngModel. You’ll need to handle that on your own. In this case, I’m going to clear the value of contact.county whenever the contact.sate changes, but only if the value contact.state isn’t the same as it’s current value (like on the initial load of the view).