Search code examples
angularjsng-options

ng-options and updating model


Under the following scenario, when a client is selected, I would like to update in the gallery model. How do I update the gallery model with the selected client?

<form novalidate>
            <div class="control-group">
                <label for="galleryName">Gallery Name:</label>
                <input value="{{gallery.galleryName}}" id="galleryName" type="text" ng-model="gallery.galleryName">
                <p>{{gallery}}</p>
            </div><!-- /control-group -->

            <div class="control-group">
                <label for="clientName">Client Name:</label>
                <select name="client" ng-model="clientList" ng-options="client.id as client.clientName for client in clients" >
                    <option value="">Choose Client</option>
                </select>
                {{clientList}}
            </div>
        </form>

Example of the gallery model:

{"id":"57","galleryName":"Sam","clientRef":"205","client":"245","favorited":"1","timestamp":"1374524146"}

My goal is to change the "client" when the clientList is changed.


Solution

  • You can use $scope.$watch, and you could do something like this

    $scope.$watch('clientList', function (oldValue, newValue) {
        $scope.gallery.client = newValue; //newValue is the client.id
    });
    

    Btw, you should rename clientList to something else, since what you select is only one item.