簡體   English   中英

使用ng-options在ng-repeat中動態選擇AngularJS-設置默認的選定選項

[英]AngularJS dynamic select within ng-repeat using ng-options - set default selected option

我想通過允許用戶根據可用的屬性名稱列表定義任意數量的排序屬性,來實現對項目列表的動態排序。 編碼:

JavaScript (控制器)

$scope.data.sortInfo = {};
$scope.data.sortInfo.availableProperties = [
    { PropertyName: "ProjectName", PropertyDisplayName: "Name" },
    { PropertyName: "LastUpdateOnAnsiStr", PropertyDisplayName: "Updated" },
    { PropertyName: "LocationsStr", PropertyDisplayName: "Locations" }
];

// array of selected properties to sort by {Name: {property name}, Direction: {0 = ASC / 1 = DESC}, Priority: {index of sort field (auto filled)} }
$scope.data.sortInfo.selectedProperties = [
    { Name: "ProjectName", Direction: 0, Priority: 0 }
];

的HTML

<td ng-repeat="currentSelectedProperty in data.sortInfo.selectedProperties track by $index">
     <!-- debug info -->
     {{currentSelectedProperty.Name}} - {{currentSelectedProperty.Direction}} - {{currentSelectedProperty.Priority}}

      <select ng-model="currentSelectedProperty.Name"
              ng-options="item as item.PropertyDisplayName for item in data.sortInfo.availableProperties track by item.PropertyName">
</td>

這樣做,可以正確顯示並填充select ,但是我沒有選擇任何選項。 我希望下拉菜單中顯示ProjectName

另外,更改選擇中的值將正確更改調試字段(名稱,方向和優先級)中顯示的信息,因此ng-model似乎可以正常工作。

我設法通過不使用ng-options並明確地ng-repeat選項來找到解決方法:

<option ng-selected="{{item.PropertyName == currentSelectedProperty.Name}}" 
        ng-repeat="item in data.sortInfo.availableProperties"
        value="{{item.PropertyName}}">
   {{item.PropertyDisplayName}}
</option>

問題:我的ng-options方法有什么問題?

角版本為1.4.3。

謝謝!

試試下面,它應該可以工作:

<select ng-model="currentSelectedProperty.Name" ng-init="currentSelectedProperty.Name=data.sortInfo.availableProperties[0]" ng-options="item as item.PropertyDisplayName for item in data.sortInfo.availableProperties track by item.PropertyName">

使用ng-init或在控制器中設置默認值。

請參閱此先前回答的問題, 如何使用ng-option設置select元素的默認值

嘗試這個,

$scope.data.sortInfo.selectedProperties =   $scope.data.sortInfo.availableProperties[0]

代碼中的問題是可用屬性和selectedproperties的對象不同。

您可以簡單地執行以下操作:

<select ng-model="currentSelectedProperty"
              ng-options="item as item.PropertyDisplayName for item in data.sortInfo.availableProperties track by item.PropertyName">

原因:currentSelectedProperty是可以被映射到的對象,這也是一個目的。 由於對象包含在數組中,因此您需要通過$ index對其進行跟蹤。

暫無
暫無

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

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