ng 选项在更改数组中的值时不会更新

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

本文关键字:更新 选项 数组 ng      更新时间:2023-09-26

我想更新选择列表中的数据,但选择不更新,确切查看但当我选择"测试"时,选择从 api 中获取的值,即使它没有列出。

例:

我选择"测试"

但选择的是"希勒斯克"

这是我的代码...

 <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);});   
                    
                    
                });

杰森:

[{"id":1,"name":"Śląsk"},{"id":2,"name":"Małopolska"},{"id":3,"name":"Mazowsze"}]

看起来像一个角度范围问题。Angular 可能已为所选部件创建了子范围。应将属性附加到对象,这将允许您使用范围继承。所以在你的控制器上....

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

然后在您的 html 中,更改 ng 模型以反映它现在是一个对象而不是一个基元。(将来,尽量不要在范围对象上使用基元,这样您不必担心处理范围问题)。

<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">

你缺少ng-model

$scope.defaultSelected = {"id":1,"name":"SSS"};
    $scope.regions = [{"id":1,"name":"Śląsk"},{"id":2,"name":"Małopolska"},{"id":3,"name":"Mazowsze"}]
    $scope.addItem = function() {
        $scope.regions.push({"id":4,"name":"Dlląsk"});
    }

.HTML

<select class="selectpicker form-control-select"
        data-live-search="true" data-size="5"
        name="voivodeship-account-creator"
        id="voivodeship-account-creator"
        ng-model="defaultSelected"
        ng-options="region.name for region in regions track by region.id" ng-model="selectedRegion">
        <option data-hidden='true'></option>
</select>
<button ng-click="addItem()">Add</button>

在这里摆弄....