how to make dropdown select a certain value from getting the id from the database?

35 Views Asked by At

The code below show a dropdown list from using ng-repeat. When I edit this entity, I have to make them show a certain value selected already than just showing a whole list. I know that I can put selected keyword when I want to select a certain value. Then what if I used ng-repeat to populate a dropdown? How can I make a dropdown choose a certain value using the id?

<div ng-if="field.name=='ClienteleId'" class="input-group inputFill">
    <select ng-disabled="defaultSaveButtons[$index]" class="form-control inputFill2"
    ng-model="field.value" ng-options="clientele.id as clientele.name for clientele in     dropdown.clienteleOptions  | orderBy:'name'  track by clientele.id"></select>
 /div>

1

There are 1 best solutions below

0
On

To set the value of a <select> in AngularJS, you need to change the variable that is set as its ng-model to one of the values in your options.

In your case, you have field.value as your ng-model, and your options use the name attribute as their label and the id attribute as their value. To have one of the items in dropdown.clienteleOptions selected by default, you need to set field.value to the id attribute of the corresponding entry in dropdown.clienteleOptions.

Imagine your options and fields look like this:

$scope.clienteleOptions = [
    {id: 1, name: 'test 1'},
    {id: 2, name: 'test 2'}
];

$scope.fields = [
    {name: 'ClienteleId', value: null}
    // ...
];

In your controller somewhere, you would have something like this to have test 2 selected:

$scope.fields[0].value = 2;

Or to make it more dynamic:

$scope.fields.forEach(function (field) {
    if (field.name === 'ClienteleId') {
        field.value = 2;
    }
});