angularJS - add a Static option with ng-options

前端 未结 4 1699
别跟我提以往
别跟我提以往 2020-12-16 23:17

I am using ng-options to print all the options for a form in my angular app. I get the value directly from my database which gives me a list of countries:

&l         


        
相关标签:
4条回答
  • 2020-12-16 23:41

    This is probably a late post but you should almost never use ng-repeat where ng-options is better suited like this case because new scopes are created in ng-repeat and thus you'd have more overhead.

    The solution to your problem is well written in the angular docs and what you need looks somewhat like

    <select ng-options="country.country for country in countries"
            ng-model="selectedCountry"
            ng-change="updateSelectedCountry(selectedCountry)"
           class="form-control">
       <option value="" disabled>Anywhere</option>
    </select>
    

    With this angular uses the value="" to set a null value and starts iteration from after that value.

    0 讨论(0)
  • 2020-12-16 23:41

    I made a slight adjustment to hassassin's fiddle. This is a little more inline with how ng-options is intended to work. Example

    var myApp = angular.module('myApp', [])
        .controller('TestController', ['$scope', function ($scope) {
            $scope.data = [1,2,3];
            $scope.sel = '';
    }]);
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
    <div ng-app="myApp">
    <div ng-controller="TestController">
        {{sel}}
        <select ng-model="sel" ng-options="val for (key , val) in data">
            <option value="">any</option>
        </select>
    </div>
      </div>

    0 讨论(0)
  • 2020-12-16 23:53

    You could always just do this:

    <select ng-model="selectedCountry" ng-change="updateSelectedCountry(selectedCountry)" class="form-control">
        <option>Anywhere</option>
        <option ng-repeat="country.country for country in countries">{{country.country}}
        </option>
    </select>
    

    Here is my fiddle example

    Hope this helps!

    0 讨论(0)
  • 2020-12-16 23:58

    You should set the value attribute in the custom option tag, in your example should be:

    <select ng-options="country.country for country in countries" ng-model="selectedCountry" ng-change="updateSelectedCountry(selectedCountry)" class="form-control">
      <option value='anyValueForThisOption'>Anywhere</option>
    </select>
    
    0 讨论(0)
提交回复
热议问题