簡體   English   中英

使用AngularJS的ng-options使用select

[英]Working with select using AngularJS's ng-options

我在其他帖子中已經閱讀過它,但我無法弄明白。

我有一個陣列,

$scope.items = [
   {ID: '000001', Title: 'Chicago'},
   {ID: '000002', Title: 'New York'},
   {ID: '000003', Title: 'Washington'},
];

我想將其渲染為:

<select>
  <option value="000001">Chicago</option>
  <option value="000002">New York</option>
  <option value="000003">Washington</option>
</select>

而且我想選擇ID = 000002的選項。

我已經閱讀過選擇並試過了,但我無法弄明白。

需要注意的一點是ngOode 需要 ngModel才能工作...注意ng-model="blah" ,它說“將$ scope.blah設置為所選值”。

試試這個:

<select ng-model="blah" ng-options="item.ID as item.Title for item in items"></select>

這里有更多來自AngularJS的文檔(如果你還沒有看到它):

對於數組數據源:

  • 數組中值的標簽
  • 選擇作為數組中值的標簽
  • 對於array中的值,按組分組標簽=按數組中的值選擇為標簽組

對於對象數據源:

  • 對象中的(鍵,值)標簽
  • 選擇對象中的(鍵,值)標簽
  • 對象中的(鍵,值)按組標記
  • 為對象中的(鍵,值)按組選擇標簽

有關AngularJS中選項標記值的一些說明:

使用ng-optionsng-options 寫出的選項標簽的值將始終是選項標簽所涉及的數組項的索引 這是因為AngularJS實際上允許您使用選擇控件選擇整個對象,而不僅僅是基本類型。 例如:

app.controller('MainCtrl', function($scope) {
   $scope.items = [
     { id: 1, name: 'foo' },
     { id: 2, name: 'bar' },
     { id: 3, name: 'blah' }
   ];
});
<div ng-controller="MainCtrl">
   <select ng-model="selectedItem" ng-options="item as item.name for item in items"></select>
   <pre>{{selectedItem | json}}</pre>
</div>

以上將允許您直接在$scope.selectedItem選擇整個對象。 關鍵是,使用AngularJS,您無需擔心選項標簽中的內容。 讓AngularJS處理; 你應該只關心你范圍內模型中的內容。

這是一個展示上述行為的plunker,並顯示HTML寫出來


處理默認選項:

我上面沒有提到一些與默認選項有關的事情。

選擇第一個選項並刪除空選項:

你可以通過添加一個簡單的ng-init來設置模型(從ng-model )到你在ng-options重復的項目中的第一個元素:

<select ng-init="foo = foo || items[0]" ng-model="foo" ng-options="item as item.name for item in items"></select>

注意:如果foo恰好被初始化為“falsy”,這可能會有點瘋狂。 在這種情況下,您最有可能想要在控制器中處理foo的初始化。

自定義默認選項:

這有點不同; 這里你需要做的就是添加一個選項標簽作為你的選擇的子項,使用空值屬性,然后自定義其內部文本:

<select ng-model="foo" ng-options="item as item.name for item in items">
   <option value="">Nothing selected</option>
</select>

注意:在這種情況下,即使您選擇了其他選項,“空”選項也將保留在那里。 對於AngularJS下的選擇的默認行為,情況並非如此。

選擇后隱藏的自定義默認選項:

如果您希望在選擇值后自定義默認選項消失,則可以將ng-hide屬性添加到默認選項:

<select ng-model="foo" ng-options="item as item.name for item in items">
   <option value="" ng-if="foo">Select something to remove me.</option>
</select>

我正在學習AngularJS,並且也在努力選擇。 我知道這個問題已經回答了,但我想分享更多的代碼。

在我的測試中,我有兩個列表框:汽車制造和汽車模型。 在選擇某些make之前,模型列表將被禁用。 如果稍后重置選擇列表框(設置為'選擇生成'),則模型列表框將再次被禁用並且其選擇也將被重置(到“選擇模型”)。 將模型作為資源檢索,而模型只是硬編碼。

制作JSON:

[
{"code": "0", "name": "Select Make"},
{"code": "1", "name": "Acura"},
{"code": "2", "name": "Audi"}
]

services.js:

angular.module('makeServices', ['ngResource']).
factory('Make', function($resource){
    return $resource('makes.json', {}, {
        query: {method:'GET', isArray:true}
    });
});

HTML文件:

<div ng:controller="MakeModelCtrl">
  <div>Make</div>
  <select id="makeListBox"
      ng-model="make.selected"
      ng-options="make.code as make.name for make in makes"
      ng-change="makeChanged(make.selected)">
  </select>

  <div>Model</div>
  <select id="modelListBox"
     ng-disabled="makeNotSelected"
     ng-model="model.selected"
     ng-options="model.code as model.name for model in models">
  </select>
</div>

controllers.js:

function MakeModelCtrl($scope)
{
    $scope.makeNotSelected = true;
    $scope.make = {selected: "0"};
    $scope.makes = Make.query({}, function (makes) {
         $scope.make = {selected: makes[0].code};
    });

    $scope.makeChanged = function(selectedMakeCode) {
        $scope.makeNotSelected = !selectedMakeCode;
        if ($scope.makeNotSelected)
        {
            $scope.model = {selected: "0"};
        }
    };

    $scope.models = [
      {code:"0", name:"Select Model"},
      {code:"1", name:"Model1"},
      {code:"2", name:"Model2"}
    ];
    $scope.model = {selected: "0"};
}

出於某種原因,AngularJS讓我感到困惑。 他們的文件非常可怕。 我們歡迎更多有關變化的好例子。

無論如何,我對Ben Lesh的答案略有不同。

我的數據集如下所示:

items =
[
   { key:"AD",value:"Andorra" }
,  { key:"AI",value:"Anguilla" }
,  { key:"AO",value:"Angola" }
 ...etc..
]

現在

<select ng-model="countries" ng-options="item.key as item.value for item in items"></select>

仍然導致選項值成為索引(0,1,2等)。

添加曲目通過修復它為我:

<select ng-model="blah" ng-options="item.value for item in items track by item.key"></select>

我想更常見的是你想要將一個對象數組添加到選擇列表中,所以我要記住這一個!

請注意,從AngularJS 1.4開始,您不能再使用ng-options,但需要在選項標簽上使用ng-repeat

<select name="test">
   <option ng-repeat="item in items" value="{{item.key}}">{{item.value}}</option>
</select>

這個問題已經回答了(順便提一下,Ben提供了非常好的和全面的答案),但我想補充一點完整性,這也可能非常方便。

在本建議的例子中:

<select ng-model="blah" ng-options="item.ID as item.Title for item in items"></select>

使用了以下ngOptions表單: select as label for value in array

Label是一個表達式,其結果將是<option>元素的標簽。 在這種情況下,您可以執行某些字符串連接,以便擁有更復雜的選項標簽。

例子:

  • ng-options="item.ID as item.Title + ' - ' + item.ID for item in items"為您提供Title - ID等標簽
  • ng-options="item.ID as item.Title + ' (' + item.Title.length + ')' for item in items"為您提供Title (X)等標簽,其中X是Title string的長度。

您也可以使用過濾器,例如

  • ng-options="item.ID as item.Title + ' (' + (item.Title | uppercase) + ')' for item in items"為您提供Title (TITLE)等標簽,其中Title屬性的Title值和TITLE是相同的值,但轉換為大寫字符。
  • ng-options="item.ID as item.Title + ' (' + (item.SomeDate | date) + ')' for item in items"為您提供Title (27 Sep 2015)等標簽,如果您的模型有屬性SomeDate

在CoffeeScript中:

#directive
app.directive('select2', ->
    templateUrl: 'partials/select.html'
    restrict: 'E'
    transclude: 1
    replace: 1
    scope:
        options: '='
        model: '='
    link: (scope, el, atr)->
        el.bind 'change', ->
            console.log this.value
            scope.model = parseInt(this.value)
            console.log scope
            scope.$apply()
)
<!-- HTML partial -->
<select>
  <option ng-repeat='o in options'
          value='{{$index}}' ng-bind='o'></option>
</select>

<!-- HTML usage -->
<select2 options='mnuOffline' model='offlinePage.toggle' ></select2>

<!-- Conclusion -->
<p>Sometimes it's much easier to create your own directive...</p>

如果您需要每個選項的自定義標題,則ng-options不適用。 而是使用ng-repeat和選項:

<select ng-model="myVariable">
  <option ng-repeat="item in items"
          value="{{item.ID}}"
          title="Custom title: {{item.Title}} [{{item.ID}}]">
       {{item.Title}}
  </option>
</select>

我希望以下內容對您有用。

<select class="form-control"
        ng-model="selectedOption"
        ng-options="option.name + ' (' + (option.price | currency:'USD$') + ')' for option in options">
</select>

它可能很有用。 綁定並不總是有效。

<select id="product" class="form-control" name="product" required
        ng-model="issue.productId"
        ng-change="getProductVersions()"
        ng-options="p.id as p.shortName for p in products"></select>

例如,您從REST服務填充選項列表源模型。 在填充列表之前已知選定的值,並且已設置。 使用$ http執行REST請求后,列表選項完成。

但是未設置所選選項。 由於未知原因,shadow $ digest執行中的AngularJS未按預期綁定。 我必須使用jQuery來設置所選。 這很重要! 陰影中的AngularJS將前綴添加到由ng-repeat選項生成的attr“值”的值。 對於int,它是“數字:”。

$scope.issue.productId = productId;
function activate() {
    $http.get('/product/list')
       .then(function (response) {
           $scope.products = response.data;

           if (productId) {
               console.log("" + $("#product option").length);//for clarity
               $timeout(function () {
                   console.log("" + $("#product option").length);//for clarity
                   $('#product').val('number:'+productId);

               }, 200);
           }
       });
}

暫無
暫無

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

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