Javascript 在 angularjs 中对数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34782033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sort array in angularjs
提问by Syed
Im working on sorting on an array using Angular JS using orderBy. But still its not getting sorted on a particular key.
我正在使用 orderBy 使用 Angular JS 对数组进行排序。但它仍然没有按特定键排序。
Here is the code
这是代码
var app = angular.module('sortModule', [])
app.controller('MainController', function($scope,$filter){
$scope.languages = [
{ name: 'English', image: '/images/english.png',key:2 },
{ name: 'Hindi', image: '/images/hindi.png',key:3 },
{ name: 'English', image: '/images/english.png',key:2},
{ name: 'Telugu', image: '/images/telugu.png',key:1 }];
var newLanguages = []
newLanguages = angular.copy($scope.languages);
function sortImages() {
$scope.languages = []
$scope.keys = []
for(language in newLanguages) {
$scope.keys.push(newLanguages[language])
}
$filter('orderBy')($scope.keys, 'key')
console.log(JSON.stringify($scope.keys))
}
sortImages();
});
});
Im planning to see sorting based on "key". telugu should come first, english next and hindi last.
我计划查看基于“键”的排序。泰卢固语应该排在第一位,英语次之,印地语最后。
回答by gaurav5430
you need to have:
你需要:
$scope.keys = $filter('orderBy')($scope.keys, 'key', false)
the order by filter returns a new array, it does not make changes to the passed array.
order by 过滤器返回一个新数组,它不会对传递的数组进行更改。
updated fiddle: http://jsfiddle.net/kjuemhua/17/
更新小提琴:http: //jsfiddle.net/kjuemhua/17/
回答by Sheetal
Remove the OrderBy from the html markup to display unordered list:
从 html 标记中删除 OrderBy 以显示无序列表:
<div ng-app="sortModule" class="nav">
<div ng-controller="MainController">
<button ng-click="sort()">Sort
</button>
<div></div>
<div >
<ul>
<li ng-repeat="lang in languages">
<span>{{lang.name}}</span>
</li>
</ul>
</div>
</div>
</div>
Now using the button sort sort the list
现在使用按钮排序排序列表
var app = angular.module('sortModule', [])
app.controller('MainController', function($scope,$filter){
$scope.languages = [
{ name: 'English', image: '/images/english.png',key:2 },
{ name: 'Hindi', image: '/images/hindi.png',key:3 },
{ name: 'English', image: '/images/english.png',key:2},
{ name: 'Telugu', image: '/images/telugu.png',key:1 }];
var newLanguages = []
newLanguages = angular.copy($scope.languages);
$scope.sort = function(){
$scope.languages = []
$scope.keys = []
for(language in newLanguages) {
$scope.keys.push(newLanguages[language])
}
$scope.keys = $filter('orderBy')($scope.keys, 'key', false);
$scope.languages = $scope.keys;
console.log(JSON.stringify($scope.keys))
}
});