Remove blank option from angularjs dropdown

Viewed 218

The function below comes from an angularjs controller and dynamically sets values for a dropdown, it works but the first option is always blank with a value of "?". How should I amend the function to either remove the blank option or set the selected option to items[0]?

--edit--

I haven't posted the full controller, which came from a 3rd party package, the controller shows the function u is called when the dropdown value changes.

There are 2 dropdowns, when one changes the other should update with new data, this part works but the new data has the extra blank option stated above.

thanks

   function u() {
          var subs;
          if (n.model.alias == "group") {
              var selectedGroup = document.getElementById("group").value;
              subs = angular.element(document.getElementById('subGroup')).controller();

              $.ajax({
                  url: "/umbraco/Api/ContentmentCustomApi/GetSubGroups",
                  type: "GET",
                  cache: false,
                  async: false,
                  data: { selectedGroup: selectedGroup }
              }).then(function (data) {
                  subs.items = data;
                });
          };
  }
      <div class="contentment" ng-class="vm.uniqueId" ng-controller="Umbraco.Community.Contentment.DataEditors.DropdownList.Controller as vm">     
        <select id="{{model.alias}}"             class="umb-dropdown"             lk-html-attributes="vm.htmlAttributes"             ng-model="model.value"           ng-change="vm.change()"       ng-options="item.value as item.name disable when item.disabled for item in vm.items">         
    
        </select> 
      </div>
1 Answers

It's expected to reassign value for model.value when you set the ngOptions.

Something like this based on the code in your question

subs.items = data;
n.model.value = subs.items[0];

The reason why the first option of the select is empty is that, the value referenced by ng-model does not exist in the list of ng-option.

Note that sometimes the value is the same but it's not the same reference.

Something for further reading:

https://docs.angularjs.org/api/ng/directive/ngOptions

By default, ngModel watches the model by reference, not value. This is important to know when binding the select to a model that is an object or a collection.

One issue occurs if you want to preselect an option. For example, if you set the model to an object that is equal to an object in your collection, ngOptions won't be able to set the selection, because the objects are not identical. So by default, you should always reference the item in your collection for preselections, e.g.: $scope.selected = $scope.collection[3].

Related