简体   繁体   中英

Pre-select an option in select based on a string

I've been searching around to see if there's some sort of equivalent function for indexOf but for select boxes that uses ng-options , but I haven't been able to find an answer.

Basically what I'm trying to do is this:

$scope.$parent.user.country = $scope.countries[0];

EDIT: I use $parent since the $scope.user object lives in the parent scope, but the select still has access to it.

But instead of $scope.countries[0] I need to select the option, which object's name property matches a string that comes from the database. So if $scope.$parent.user.country is equal to "Sweden" , this option should be pre-selected.

How can I achieve this?

This is a snippet from the JSON will creates the select box:

[
  {"name": "Sweden", "code": "SE"}, 
  {"name": "Switzerland", "code": "CH"}, 
  {"name": "Syrian Arab Republic", "code": "SY"}
]

This is the select box:

<select ng-model="user.country" ng-options="country as country.name for country in countries"></select>

In your controller, just set $scope.user.country to the option whose name is equal to $scope.$parent.user.country .

$scope.user.country = $scope.countries.filter(function(country) { 
    return country.name === $scope.$parent.user.country;
})[0]

Note that filter returns an array so make sure you just get the first item.

Any of you red docs??

<label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
<select aria-label="ngSelected demo">
  <option>Hello!</option>
  <option id="greet" ng-selected="selected">Greetings!</option>
</select>

ng-selected='selected' <- word selected in apostrophes points to $scope.selected. Just put your selection value there.

Here you have docs link: ngSelected

Here you have my example. I bring you my whole javascript with reading 4 selects from database dependant on selection in each other and after this you will see my whole jade part of this code. You may copy this sollution with your names.

.controller('datatableRelationController', ['$scope', '$http',
    function ($scope, $http) {
        $scope.relations = [];
        $scope.tables = [];


        $scope.firstTableColumns = [];
        $scope.secondTableColumns = [];
        //display menu with tables
        $http.get('/api/datatable/list/')
            .success(function (json_data, status, headers, config) {
                for (key in json_data) {
                    var fields = json_data[key]['fields'];
                    $scope.tables.push({name: fields['name']});
                }
            })
            .error(function (data, status, headers, config) {
                Materialize.toast("Błąd pobierania tabel", 2000);
            });

        $scope.addRelation = function () {
            var data = {
                source_table: $scope.firstTable.name,
                source_column: $scope.firstTableSelectedColumn.name,
                dest_table: $scope.secondTable.name,
                dest_column: $scope.secondTableSelectedColumn.name,
                relation_type: 'normal'
            };
            apiPOST('/api/relation/add/', data, $http)
                .success(function (data, status, headers, config) {
                    Materialize.toast('Relacja dodana.', 2000);
                    $scope.relations = [];
                    $scope.tables = [];


                    $scope.firstTableColumns = [];
                    $scope.secondTableColumns = [];
                })
                .error(function (data, status, headers, config) {
                    Materialize.toast('Błąd dodawania relacji.', 2000)
                });
        };

        var getColumns = function (tableName, destination) {
            $http.get('/api/worktable/fields/get/' + tableName)
                .success(function (json_data, status, headers, config) {
                    var fields = json_data[0];
                    for (key in fields) {
                        destination.push({name: fields[key]});
                    }
                })
                .error(function (data, status, headers, config) {
                    Materialize.toast("Błąd pobierania kolumn z tabeli", 2000);
                });
        }

        $scope.firstTableChange = function (firstTable) {
            getColumns(firstTable.name, $scope.firstTableColumns);
        };

        $scope.secondTableChange = function (secondTable) {
            getColumns(secondTable.name, $scope.secondTableColumns);
        };
    }
]);

JADE PART:

        .row
            .col.l5.m6.s12.offset-l1
                .form
                    .input-field
                        select.browser-default(ng-model="firstTable", ng-change="firstTableChange(firstTable)", ng-options="table.name for table in tables", material-select)
                            option(value="", disabled, ng-selected) Wybierz pierwszą tabelę
                div(ng-show="firstTable || secondTable")
                    .form(ng-show="firstTable")
                        .input-field
                            select.browser-default(ng-model="firstTableSelectedColumn", ng-change="firstTableSelectedColumn", ng-options="column.name for column in firstTableColumns", required, material-select)
            .col.l5.m6.s12
                .form
                    .input-field
                        select.browser-default(ng-model="secondTable", ng-change="secondTableChange(secondTable)", ng-options="table.name for table in tables", material-select)
                            option(value="", disabled, ng-selected) Wybierz drugą tabelę
                div(ng-show="firstTable || secondTable")
                    .form(ng-show="secondTable")
                        .input-field
                            select.browser-default(ng-model="secondTableSelectedColumn", ng-change="secondTableSelectedColumn", ng-options="column.name for column in secondTableColumns", required, ng-show="secondTable", material-select)
        .row
            .col.s12.center-align
                button.btn.orange.lighten-2.weaves-effect.white-text(ng-click="addRelation()") Zastosuj

So after some testing I found a solution which works, I managed to do so with @sq1020's answer as a foundation:

var index;

$scope.$parent.user.country = $scope.countries[$scope.countries.map(function(country, i) {

  if (country.name === $scope.$parent.user.country.name) {
    index = i;
    return i;
  }
})[index]];

You can just do this

<select ng-model="user.country" ng-options="country.name as country.name for country in countries"></select>

And it should work

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