如何在 angularjs 中正确 select 数组

How to select an array properly in angularjs

我想按多个属性对项目列表进行排序。所以我使用了一个绑定在变量中的数组。

一切正常,直到我让用户使用 select 选择订单选项。当我的数组有超过 1 个值时它会中断......而且它似乎默认为 track by $index 顺序。

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>

我应该怎么做才能允许按多个属性排序?

它似乎正在使用 ng-options。我猜 "value" 是将值转换为字符串而不是将其保存为数组。

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" ng-options="item as index for (index, item) in my_selected">
  </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>

试试这个。希望它能帮助你。谢谢。

<div ng-repeat="item in items | orderBy:'a'">{{item.a}} {{item.b}}</div>

@Poney 给了我正确的答案。

OPTION 将我的 array 转换为 CDATA object。不确定 CData 数组是什么样的,但避免它解决了我的问题。

https://www.w3.org/TR/html401/interact/forms.html#edef-OPTION.

为了保留我的数组,我必须将 ng-optionsng-change 结合起来并在 javascript 函数中进行更改。