Search code examples
angularjsasp.net-mvc-4angularjs-ng-options

Add two options to select list top and bottom using ng-options in AngularJS


I am trying to populate a drop down list in a cshtml page using Angular. The Angular controller calls a service using Web API to return values. I have added a default selected item to instruct users to select an item from the list. I also want to append 'Other' to the end of the select list.

I prefer to use the ng-options if I can. I know how to do this using ng-repeat.

The markup is as follows:

<div class="formElement">
  <label for="companySelect" class="required long">{{'CompanyName'}}</label>
  <select name="companySelect" id="companySelect" ng-change="selectCompany()" ng-model="data" data-ng-options="company.CompanyName 
    for company indata.companySelect | orderBy:'CompanyName' track by company.CompanyName">
    <option value="">Please Select</option>
    <option value ="other">Other</option>
  </select>
</div>

Solution

  • I guess if your webapi return some json data, you got that values by $scope.company in your angular controller

    • Add Please Select to top element of your array

    You can do it by using array unshift

    $scope.company.unshift("Please Select")// May it be a object
    
    • Add Others to bottom element of your array

    You can do it by using array push

    $scope.company.push("Other")// May it be a object