Search code examples
angularjsng-optionsangularjs-select

Angular setting a selected attribute with ng-options


Im populating the values and display names for a select based on a JSON call. In the same call, I'm pulling from a nested array to get a default account value (if it exists). so I have a scope that is holding that default account value, and the select is populating, but for the life of me, I can't figure out how to get the select attribute to apply to the object in the array that has a value that corresponds to the default value.

Essentially, I just want to apply "selected" to the option if the default account ID exists in the array.

Additionally, I cannot change the ng-model of the select because its tied into the form collection function.

Also, Im open to using ng-repeat vs ng-options, just couldn't figure it out with repeat so I moved to the options paradigm.

Any assistance would be grateful! HTML:

<select class="form-control" id="authQAccount" name="authQAccount" ng-model="authFields.accountID" ng-init ng-options="item as item.name for item in accounts track by item.ID" ng-selected="$scope.defaultAcct" required>
    </select>

In my controller:

$http.get('/api/assessment/authorize').success(function(data, status, headers, config) {
    $scope.content = data.data;
    //Pop the defaults and user options
    $scope.languages = [];
    angular.forEach(data.data.languages, function(value, key) {
          $scope.languages.push(value);
    });
    $scope.accounts = [];
    angular.forEach(data.data.accounts, function(value, key) {
          $scope.accounts.push(value);

    }); 

    $scope.defaultAcct = data.data.defaultAccount;

The data Im getting:

"data": {
    "defaultAccount": "6481004",
    "defaultLanguage": "en_us",
    "defaultAddonBody": "Test Email for Default",
    "accounts": [{
        "ID": "6481004",
        "name": " ABC Company, Inc.            "
    }, {
        "ID": "6481619",
        "name": "EDF Company - Personal                "
    }

Solution

  • ng-selected only works on option elements and not on the select element itself. I don't think you can achieve what you want here with ng-options, if ng-model isn't set to a matching item then there's no way for the select to have that item selected.

    Unless you only want it to appear selected, then you can add <option value="" ng-if="defaultAccount">{{defaultAccountName}}</option>. But then you'd have 2 items for the same value, you could either remove the default account from the list of options or keep the two items but with one of them prefixed as (Default). The second option lets users still select the default option without losing their choice later on, in case the default changes. This also means your form has the default selected without having to change the outer model.