Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-options do not update when changing values in the array

I would like to update the data in select list but select not updating, exactly view but When I select 'test' is selected the value taken from the api even though it is not listed.

Example:

I choose 'test'

but selected is 'Śląsk'

Here is my code...

 <div ng-controller="selectController"
        class="form-group text-primary col-lg-4 col-md-6 col-sm-6 col-xs-12">
        <label for="voivodeship-account-creator">Województwo</label>

<select class="selectpicker form-control-select"
        data-live-search="true" data-size="5"
        name="voivodeship-account-creator"
        id="voivodeship-account-creator"
        ng-options="region.name for region in regions track by region.id" ng-model="selectedRegion">

        <option data-hidden='true'></option>
</select>

</div>

JS:

angular
        .module('main')
        .controller(
                'selectController',
                function($scope,$http,$rootScope) {
                    $scope.selectedRegion = '';
                    $scope.regions = [
                                      {'name': 'test',
                                       'id': 1}
                                    ];
                    
                    $http.get('api/regions')
                        .then(function(response) {
                            $scope.regions = response.data;
                              console.log($scope.regions);});   
                    
                    
                });

JSON:

[{"id":1,"name":"Śląsk"},{"id":2,"name":"Małopolska"},{"id":3,"name":"Mazowsze"}]
like image 729
Doni Avatar asked Nov 08 '22 19:11

Doni


1 Answers

Looks like an angular scoping issue. Angular may have created a child scope for the select part. You should attach your property to an object, which will allow you to make use of scope inheritance. So on your controller....

$scope.selectedRegion = {selection: ""};

And then in your html, change the ng-model to reflect it's now an object instead of a primitive. (In the future, try not to use primitives on your scope objects, it makes you not have to worry about dealing with scoping issues).

<select class="selectpicker form-control-select"
        data-live-search="true" data-size="5"
        name="voivodeship-account-creator"
        id="voivodeship-account-creator"
        ng-options="region.name for region in regions track by region.id" ng-model="selectedRegion.selection">
like image 101
whatoncewaslost Avatar answered Nov 14 '22 23:11

whatoncewaslost