I want to order a list of items by multiple properties. So I use an array that I bind in a variable.
Everything works fine until I let the user choose order options with a select
. It breaks when my array has more than 1 value... and it seems to defaults to the track by $index
order.
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function($scope){
$scope.items = [
{a: "3", b: "First"},
{a: "2", b: "Second"},
{a: "1", b: "Third"}
];
$scope.my_orderby = ['a','b'];
$scope.my_selected = {
a: ['a'],
b: ['b'],
ab: ['a','b'],
ba: ['b','a']
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="my_orderby.push(my_orderby.shift())">In place: {{my_orderby}}</button>
<select ng-model="my_orderby">
<option value="{{v}}" ng-repeat="(k,v) in my_selected">{{k}}</option>
</select>
<button ng-click="items.push(items.shift())">{{items}}</button>
<hr/>
<div ng-repeat="item in items | orderBy:my_orderby track by $index">{{item.a}} {{item.b}}</div>
</div>
How am I supposed to do to allow sorting by multiple properties?
@Poney gave me the right lead for an answer.
OPTION
converts my array
to CDATA object
. Not sure what a CData array looks like, but avoiding it solved my issue.
https://www.w3.org/TR/html401/interact/forms.html#edef-OPTION.
To preserve my array, I had to combine ng-options
with ng-change
and do the change in a javascript function.