我有一个看起来像的对象:
{
3019: 'Javascript',
3046: 'Css'
}
然后,我在select
中显示此对象:
<select
ng-model="langChoosed"
ng-options="key as value for (key, value) in progLanguages"
></select>
我需要对select中的项进行排序,但orderBy
过滤器似乎只适用于数组,如何使其与对象一起使用?
答案 0 :(得分:3)
NO order by无法应用于普通对象,或者您可以在控制器中定义一个方法将对象转换为数组
<强>样本强>
var app = angular.module('todoApp', []);
app.controller("dobController", ["$scope",
function($scope) {
$scope.progLanguages = {
3019: 'Javascript',
3046: 'Css'
};
$scope.templatesAry = function() {
var ary = [];
angular.forEach($scope.progLanguages, function(val, key) {
ary.push({
id: key,
lang: val
});
});
return ary;
};
}
]);
<!DOCTYPE html>
<html ng-app="todoApp">
<head>
<title>To Do List</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
</head>
<body ng-controller="dobController">
<select class="form-control" id="selection" ng-model="currentSelected" ng-options="selection.id as selection.lang for selection in templatesAry() | orderBy:'lang'"></select>
</body>
</html>
答案 1 :(得分:1)
对象键是无序的 - 因此您无法对它们进行排序。将您的对象转换为数组,对其进行排序,然后使用它:
var sortedArrayFromObject = Object.keys($scope.progLanguages).map(function(key) {
var obj = {};
obj["key"] = key;
obj["value"] = $scope.propLanguages[key];
return obj;
});
//Sort it
sortedArrayFromObject.sort(function(a, b) {
return +a.key - +b.key; //since all keys are strings - do an int cast with "+"
});
//Assign it
$scope.sortedArray = sortedArrayFromObject;
使用它:
<select
ng-model="langChoosed"
ng-options="item.key as item.value for item in sortedArray"></select>
答案 2 :(得分:-1)
对你来说还好吗?
var myObj = {
3046:'Css',
3019:'Javascript'
};
var keys = [];
angular.forEach(myObj, function(value,key){
keys.push(key);
});
keys.sort();
$scope.myObj2={};
angular.forEach(keys, function(key){
$scope.myObj2[key]=myObj[key];
});
和你的HTML
<select
ng-model="langChoosed"
ng-options="key as value for (key, value) in myObj2"
></select>