簡體   English   中英

設置默認值選擇AngularJS

[英]Set default Value select AngularJS

我用外部json文件填充我的選擇。 一切正常。 但是,如何設置選擇的默認值呢? 我想將其設置為“美國”,這是我的選項值之一,該值是從json文件country.json中加載的。

我試圖這樣做:

 ng-init="selectionCountry = options['United States']

或帶有編號,因為國家處於第一位...

ng-init="selectionCountry = options[0]

但是,它不起作用。 有小費嗎?

HTML

<select id="country" class="form-control country" ng-model="selectionCountry">
    <option value="" ng-options="country in data.locations.countries | orderBy:'name'">{{country.name}}</option> 
</select>

腳本

.controller('NewInvoiceCtrl', ['$scope', '$translate', '$modal', '$window', '$filter', '$http', '$timeout',
function($scope, $translate, $modal, $window, $filter, $http, $timeout) {

    // load and populate Json in country select
    $scope.data = {
        "locations": {}
    };

    $http.get('l10n/countries.json')
      .then(function(res) {
        $scope.data.locations.countries = res.data;
        $scope.$$phase || $scope.$apply();
        // set default
        $scope.selectionCountry = $scope.data.locations.countries[1];
      });
 }])

范例JSON

  {
    "alpha2": "US",
    "alpha3": "USA",
    "countryCallingCodes": [
      "+1"
    ],
    "currencies": [
      "USD"
    ],
    "ioc": "USA",
    "name": "United States",
    "status": "assigned"
  },

您可以使用ngOptions指令,並在控制器中運行orderBy過濾器:

HTML

<select id="country" class="form-control country" ng-disabled="!data.locations.countries.$resolved" ng-model="selectionCountry" ng-options="country.name for country in data.locations.countries">
</select>

調節器

controller("NewInvoiceCtrl", function ($scope, $http, $filter) {
  $scope.data = {
    locations: {
      countries: []
    }
  };

  $scope.data.locations.countries.$resolved = false;

  $http.get('countries.json').success(function(countries) {
    $scope.data.locations.countries.length = 0;
    Array.prototype.push.apply($scope.data.locations.countries, $filter('orderBy')(countries, 'name'));
    $scope.selectionCountry || ($scope.selectionCountry = $scope.data.locations.countries[1]);
    $scope.data.locations.countries.$resolved = true;
  });
});

此外,添加$resolved字段可以使您禁用該字段,直到填充了國家/地區列表為止(這與$resource操作類似)。

這是一個工作示例: http : //plnkr.co/edit/vuKsqU5q52s7pfOPcGLI?p=preview


或者,如果要基於名稱選擇默認值:

$scope.data.locations.countries.$default = 'United States';

// when setting $scope.selectionCountry
$scope.selectionCountry = $filter('filter')($scope.data.locations.countries, {name: $scope.data.locations.countries.$default})[0];

這是“按名稱”過濾器的示例: http : //plnkr.co/edit/Czy53cTfptPdyAPBr3eS?p=preview

看來這應該工作。 我不確定為什么您要調用$scope.$apply()

$http.get('l10n/countries.json')
  .then(function(res) {
    $scope.data.locations.countries = res.data;
    $scope.selectionCountry = $scope.data.locations.countries[0];
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM