簡體   English   中英

angularJS - 使用ng-options添加靜態選項

[英]angularJS - add a Static option with ng-options

我正在使用ng-options在我的角度應用程序中打印表單的所有選項。 我直接從我的數據庫中獲取了值,這給了我一個國家列表:

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

這里加載頁面時,選擇不會顯示任何內容,即沒有占位符,而我想打印一個靜態值,如“任何地方”,而不必將其添加到我的“國家/地區”列表中。

我試過這個:

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

但它不起作用

有誰知道如何解決這個問題?

謝謝

這可能是一個遲到的帖子,但你幾乎不應該使用ng-repeat,其中ng-options更適合這種情況,因為新的范圍是在ng-repeat中創建的,因此你會有更多的開銷。

你的問題的解決方案很好地寫在角度文檔中,你需要的東西看起來有點像

<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>

使用此角度使用value=""來設置空值並從該值之后開始迭代。

你總是可以這樣做:

<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>

這是我的小提琴示例

希望這可以幫助!

我對哈薩辛的小提琴做了一點調整。 這與ng-options工作ng-options更為一致。

 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> 

您應該在自定義選項標記中設置value屬性,在您的示例中應該是:

<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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM