How to make "data-Binding" of two variables in the same select?

Asked

Viewed 157 times

0

I have this code that is making vm.service.type = serviceType.name :

   <div class="form-group ">
        <label for="field_type"><b>Type</b></label>
        <div class="input-icon right">
            <select required class="form-control"
                    id="field_type"
                    name="type"
                    ng-model="vm.service.type"
                    ng-options="serviceType.name as serviceType.name for serviceType in vm.servicetypes">
                <option></option>
            </select>
        </div>
        <div ng-show="vm.service.type==null" class="form-group has-error">
            <p class="help-block" ng-show="vm.service.type==null" data-translate="entity.validation.required">
                This field is required.
            </p>
        </div>
    </div>

How do I get vm.service.serviceTypeId = serviceType.id... This without adding another field to the form.

Note: These variables already exist in the controller and I already have everything necessary to do what I want.

2 answers

0

I guess just put it in the controller

vm.service.id  = vm.service.type ;

The JS will reference the same memory space and any changes in type will reflect on id

But if it doesn’t work perfectly you can also use ng-change like this:

<select required class="form-control"
    id="field_type"
    name="type"
    ng-model="vm.service.type"
    ng-change="vm.service.id = vm.service.type"
    ng-options="serviceType.name as serviceType.name for serviceType in vm.servicetypes">
        <option></option>
</select>

0

I would simplify the field ng-options, in order to simplify its reading.

When we have a array composed of objectos, while iterating on it the item refers the object, so I chose the property .name for the text of <option> and in the ng-change declare that the vm.service.serviceTypeId is equal to property .id of item.

<select required class="form-control"
                id="field_type"
                name="type"
                ng-model="vm.service.type"
                ng-options="item.name for item in vm.servicetypes"
                ng-change="vm.service.serviceTypeId=item.id">
</select>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.