1

I'm trying to set the default item of a select box on load using angularjs.

I load both select boxes from 2 json's, so the second select box, named 'city' relies off the first select box 'country':

  <label>Country:</label>
  <select name="country" ng-model="form.country" 
        ng-options="c.n for c in countryList" 
        ng-change="countryChanged()" required></select>

  <label>City:</label>
  <select name="city" ng-model="form.city" 
        ng-options="c for c in cityList" required></select>

PLUNKER http://plnkr.co/edit/hKZLbMbwGfmaa8CtSy0H?p=preview

It loads the select boxes using $http.get. It loads all well and good if i default it to the first option. But lets say, I want to specify a certain option to be selected on load, but I can only send it a particular value from the json, how would I do this? In the code below, the commented line is what I've tried, but all it does is load the correct city list, but leave the country select box unselected.

countries.json

[
  {"c":"au","n":"Australia","g":"1"},
  {"c":"fr","n":"France","g":"2"},
  {"c":"ge","n":"Germany","g":"2"}
]

Controller:

$http.get('countries.json')
  .success(function (data) {
    $scope.countryList = data;
    $scope.form.country = data[0];
    // $scope.form.country.c = 'fr'; <<<--- *trying to set default*
    $scope.countryChanged();
});

$scope.countryChanged = function() {

  $http.get($scope.form.country.c + '-cities.json')
    .success(function (data) {
      $scope.cityList = data;
      $scope.form.city = data[0];
    });
}

Also, if there is a better way to achieve this, please post it.

Note: I can't join the json up. I split it because in the real world, there could be 100 countries each with 100 cities each and the json would be quite massive.

4

2 回答 2

3

不确定,但这是否满足要求? http://plnkr.co/edit/rBDVzg7iXfaHu4XmiVsb?p=preview

var selectCountry = function( data, code ) {
  for ( var i = 0; i < data.length; i++ ) {
    var country = data[ i ];
    if ( country.c !== code ) { continue; }
    return country
  }
};

$http.get('countries.json')
  .success(function (data) {
    $scope.countryList = data;
    $scope.form.country = selectCountry( data, 'fr');
    $scope.countryChanged();
});
于 2013-05-01T06:53:22.823 回答
1

只需在控制器内部的第 12 行设置:

$scope.form.country = data[1];

它将法国设置为默认值,希望我理解你的问题。

于 2013-05-01T07:00:05.097 回答