Saturday, May 23, 2015

Using Select ng-options and ng-model binding

I found it really difficult to get the select with options working in a two way databinding with AngularJS.
When I insert data I want it not to default, but in change mode I want it to default to the right object.  (the previous selected during insert).

After searching through different examples I finally got it to work as I want it.

In this example I'm selecting a customer for a work log administration.
There are two parts to it.

1. A controller part.
2. A HTML part.

I'm using bootstrap for my HTML formatting, but the example can be used plain also.

Here is the HTML part:



<select ng-model="SelectedCustomer" class="form-control"
  ng-options="Customer.customername for Customer in CustomerData.Customers.items track by Customer.customername"
     style="width: 444px;" required="required">
</select>


All I do in the controller for the update part is set the right model cutomer from my releated object like:

$scope.SelectedCustomer=$scope.WorklogData.currentWorklog.customer;

So the model in ng-model really reflects the object.