简体   繁体   中英

Load default option of database into selected option

I have a function that load a simple select like:

function cargarCatalogo() {
            apiService.get("../../api/Catalogo/GetCatalogoPadre/" + $scope.Catalogo + "/",
                null,
                function(res) {
                    $scope.Catalogos = res.data;
                    $scope.selected = $scope.Catalogos[0];
                   inicial
                    $scope.filtro($scope.selected);
                },
                errorCatalogo);
        }

As you can see I select first option as default with $scope.selected = $scope.Catalogos[0]; Problem is I don´t want that option as selected I want to be selected value of database because I´m ussing Edit View.

My table is like this:

+--------+----------+---------+
|     ID |  Nombre  | PadreID |
+--------+----------+---------+
|      1 | KENWORTH |       0 |
|      2 | VOLVO    |       0 |
|      3 | T6000    |       2 |
|      4 | T800     |       1 |
+--------+----------+---------+

If I edit register T6000 I will receive KENWORTH and VOLVO in select, but PadreID equals to 2, so I want a default option will be 2? what I need to change as selected value? Regards

HTML:

<select class="form-control" ng-hide="Catalogos.length==0" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos "></select>

$scope.selected = $scope.Catalogos[0]; result:

在此处输入图片说明

if you have the id of the needed select item, you can use ng-options="item.Codigo as item.Nombre for item in Catalogos "> the ng-model of the select will hold the Codigo and the view to the user will show Nombre

can you try this <select class="form-control" ng-hide="Catalogos.length==0" ng-change="filtro(selected)" ng-model="selected.Codigo" ng-options="item.Codigo as item.Nombre for item in Catalogos"></select>

I personally find the syntax ng-options difficult to read and understand, I've always preferred using ng-repeat with ng-bind , ng-value , and ng-selected to achieve similar results. Here's how you can accomplish this using an alternative method:

<select class="form-control" ng-hide="Catalogos.length==0" ng-change="filtro(selected)" ng-model="selected">
        <option ng-repeat="item in Catalogos" ng-bind="item.Nombre" ng-value="item.Codigo" ng-selected="item.ID === object.ID"></option>
</select>

I'm not sure how you're wanting to set which option is selected, but to use ng-selected , you need any property in the current item to evaluate to true when compared with another value.

ngSelected docs: https://docs.angularjs.org/api/ng/directive/ngSelected

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM