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.

2 Answers 2

3

Not sure, but does this satisfy the requirement? 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();
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Pretty much what I was after. Though I thought there would have been an 'angularjs' way to do it. Angularjs needs some json querying stuff in there (coughlinq) ;)
1

Just set inside your controller at line 12:

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

It sets France as default, Hope I understood your question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.