在AngularJS中使用ng-options设置填充的选择菜单的“选定”选项

时间:2017-03-04 13:17:16

标签: javascript angularjs

我想通过AngularJS ng-option指令填充选择菜单,并选择默认的预定义选项。

AngularJS提取的JSON如下所示:

{"AF":"Afghanistan","AX":"\u00c5land Islands","AL":"Albania","DZ":"Algeria","AS":"American Samoa","AD"}

填充选择菜单的代码有效:

 angular.module('drpdwnApp', []).controller('drpdwnCtrl', function ($scope, $http) {
     $scope.selectedCountries = null;
     $scope.countries = [];

     $http({
              method: 'GET',
              url: '/api/getCountries'
     }).success(function (result) {
              $scope.countries = result;
     });
 });

选择菜单的HTML:

<select name="property_country" ng-model="drpdpwnvalue" ng-options="key as value for (key , value) in countries track by key">
     <option value="">Please choose</option>
</select>

现在,让我们假设我想用键“AL”作为选定的默认选项来定义国家/地区。如何实现这一目标?

3 个答案:

答案 0 :(得分:3)

只需将$scope.drpdpwnvalue设置为&#39; AL&#39;在控制器中:

angular.module('drpdwnApp', []).controller('drpdwnCtrl', function ($scope, $http) {
     $scope.selectedCountries = null;
     $scope.countries = [];
     $scope.drpdpwnvalue = 'AL'; // this line is added
     $http({
              method: 'GET',
              url: '/api/getCountries'
     }).success(function (result) {
              $scope.countries = result;
     });
 });

ng-options与ng-model同步,因此只需操作ng-model值,另一部分由角度

处理

<强>更新 我做了一些调试,发现track by key是问题所在。所以删除它。我还创建了Address space,看看。

答案 1 :(得分:0)

在选项元素上尝试ng-selected

<select ng-model="drpdpwnvalue" ng-model="selectedCountries">
     <option value="{{key}}" ng-repeat="key as value for (key , value) in countries track by key" ng-selected="key === 'AL'">{{value}}</option>
</select>

答案 2 :(得分:0)

我终于通过简单地使用JQuery实现了它,因为两个Angular解决方案都没有为我正常工作:

    $( document ).ready(function() {
        $.getJSON("/api/getCountries", function(result) {
            var options = $("select[name=property_country]");

            $.each(result, function(key, value) {
                options.append($("<option />").val(key).text(value));
            });

            $('select[name=property_country] option[value="AL"]').attr("selected", "selected");
        });
    });

然而,这只是供参考,不会是JQuery实现的接受答案。