gpt4 book ai didi

AngularJs 在 ngRepeat 中对对象进行排序

转载 作者:行者123 更新时间:2023-12-03 06:57:02 24 4
gpt4 key购买 nike

我正在使用 AngularJs,发现在模板中对哈希对象的属性进行排序时出现问题。
我的对象是这样的:

function TestCtrl($scope){
$scope.week = {'MONDAY': ['manuel'], 'TUESDAY': [], 'WEDNESDAY': ['valerio'], 'THURSDAY': ['manuel', 'valerio'], 'FRIDAY': []}
}

现在,当我尝试在模板中打印这些值时:

<div ng-repeat="(day, names) in week">
<span>{{day}}</span>
<ul> <li ng-repeat="name in names">{{name}}</li> </ul>
</div>

打印日期的顺序不同:FRIDAY MONDAY THURSDAY TUESDAY WEDNESDAY

我尝试应用过滤器 orderBy 但我认为它不适用于对象,而仅适用于数组...

如何订购?

最佳答案

根据 AngularJS docs (版本1.3.20):

You need to be aware that the JavaScript specification does not define what order it will return the keys for an object. In order to have a guaranteed deterministic order for the keys, Angular versions up to and including 1.3 sort the keys alphabetically.

解决方法是使用键数组:

function TestCtrl($scope){
$scope.week = {
'MONDAY': ['manuel'], 'TUESDAY': [],
'WEDNESDAY': ['valerio'], 'THURSDAY': ['manuel', 'valerio'],
'FRIDAY': []}

$scope.weekDays = ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY"];
}

使用 View 中的数组进行迭代:

<div ng-repeat="day in weekDays">
<span>{{day}}</span>
<ul> <li ng-repeat="name in week[day]">{{name}}</li> </ul>
</div>
<小时/>

从 AngularJS 版本 1.4.6 更新 docs :

Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser when running for key in myObj.

关于AngularJs 在 ngRepeat 中对对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18124665/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com