0

I want to implement a dynamic sort into a list of items, by allowing the user to define any number of sort properties based on an available list of property names. The code:

JavaScript (controller)

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

Doing this, select is correctly displayed and populated, but I have no option selected. I expect to have ProjectName displayed in the drop-down.

Also, changing the value in the select will correctly change displayed information in the debug fields (Name, Direction and Priority), so ng-model seems to work properly.

I have managed to find a workaround by not using ng-options and explictly ng-repeat the options:

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

Question: what is wrong with my ng-options approach?

Angular version is 1.4.3.

Thanks!

4

4 回答 4

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">
于 2016-06-28T16:25:57.717 回答
0

在控制器中使用ng-init或设置默认值。

请参阅此先前询问/回答的问题如何使用 ng-option 设置选择元素的默认值

于 2016-06-28T16:21:26.390 回答
0

你可以简单地做:

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

原因: currentSelectedProperty是一个对象,它可以映射到也是一个对象的item 。由于对象包含在数组中,因此您需要通过 $index 来跟踪它。

于 2016-06-28T19:55:18.250 回答
0

尝试这个,

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

代码中的问题是可用属性和选定属性的对象不同。

于 2016-06-28T16:35:27.960 回答