angularjsng-optionsng-init

Angular setting selected using ng-model, ng-init, ng-options and form collection


I'm trying to set the selected option on a select element dynamically from a JSON call. I am able to set it if the options are static using this method, but for the life of me, I can't get it to set when populating the options using either ng-options or ng-repeat. Here is my HTML for one drop-down:

<select class="form-control" id="authQLang" name="authQLang" ng-model="content.languages" ng-options="item as item.name for item in languages track by item.code"  ng-init="content.languages == defaultLang" required>
    <option value="">Select a language</option>

    </select>

And the code in my controller:

$scope.content = data.data;
    $scope.defaultAcct = data.data.defaultAccount.ID;
    $scope.defaultLang = data.data.defaultLanguage.code;
    $scope.accounts = [];
      angular.forEach(data.data.accounts, function(value, key) {
          $scope.accounts.push(value);
      });
    $scope.languages = [];
      angular.forEach(data.data.languages, function(value, key) {
          $scope.languages.push(value);
      });

And the JSON format:

{
"code": 0,
"message": "",
"data": {
    "defaultAccount": {
        "ID": "6481618",
        "name": "Account X"
    },
    "defaultLanguage": {
        "code": "en-US",
        "name": "English US"
    },
    "accounts": [{
        "ID": "6481004",
        "name": " Account A."
    },...
    "languages": [{
        "code": "en-us",
        "name': "English US"
    },...

Solution

  • Get rid of the ng-init, you're much better setting this value in the controller. Also changing it from the controller will change the selection.

    <select class="form-control" id="authQLang"
      name="authQLang" ng-model="content.languages"
      ng-options="item as item.name for item in languages track by item.code"
      required>
        <option value="">Select a language</option>
    </select>
    

    Then in your controller:

    $scope.content = data.data;
    $scope.defaultAcct = data.data.defaultAccount.ID;
    $scope.defaultLang = data.data.defaultLanguage.code;
    $scope.accounts = [];
      angular.forEach(data.data.accounts, function(value, key) {
          $scope.accounts.push(value);
      });
    $scope.languages = [];
      angular.forEach(data.data.languages, function(value, key) {
          $scope.languages.push(value);
      });
    
    # add this:
    $scope.content.languages = $scope.defaultLang
    

    and just update $scope.content.languages any time you want to change the selection.

    Oh, and you had == in your ng-init which would have prevented the initial value setting correctly.