2016-06-28 9 views
0

利用可能なプロパティのリストに基づいて任意の数のソートプロパティを定義できるようにすることで、名前。コード:ng-repeatを使用してng-repeat内のAngularJS動的選択 - 既定の選択されたオプションを設定

は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が表示されると思います。

また、selectの値を変更すると、デバッグフィールド(名前、方向、優先度)に表示される情報が正しく変更されるため、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・オプション・アプローチと間違って何ですか?

角度バージョンは1.4.3です。

ありがとうございます!

+0

currentSelectedProperty.Nameの値は何ですか? –

+0

'currentSelectedProperty.Name'はどちらの場合でも' 'ProjectName''です。 – Alexei

答えて

1

は、以下試してみてください。この以前に尋ねた/回答の質問を参照してください、それが動作するはずです:

<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"> 
+0

それは働いた。ありがとうございました!しかし、 'currentSelectedProperty.Name'は文字列であり、' data.sortInfo.availableProperties [0] 'は' {PropertyName、PropertyDisplayName} 'オブジェクトであるため、ちょっと変わったようです。 – Alexei

+0

はい、その理由は:no-optionsパラメータに基づいて、オブジェクト(オブジェクト)がモデルになり、item.PropertyDisplayNameが表示値になることが明らかです。ここでドロップダウン選択を変更する必要がある場合は、ng-modelとバインドされた変数にモデルを割り当てる必要があります。また、javascriptでは、任意の値を任意の変数に再割り当てできます。だから当初のcurrentSelectedProperty.Nameは文字列になりますが、それをモデルに代入するとオブジェクトになりました。 –

0

はこれを試してみてください、あなたのコード内の問題は、あなたが持っているということです

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

使用可能なプロパティと選択されたプロパティの異なるオブジェクト。

0

あなたは簡単に行うことができます。

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

理由: currentSelectedPropertyも対象です項目にマッピングすることができるオブジェクトです。オブジェクトは配列に格納されているので、$ indexでそれを追跡する必要があります。

関連する問題