Javascript AngularJS orderBy数组索引
我有一个ng重复,看起来像这样:Javascript AngularJS orderBy数组索引,javascript,html,arrays,angularjs,Javascript,Html,Arrays,Angularjs,我有一个ng重复,看起来像这样: <div ng-app="questionnaire"> <div ng-controller="QuestionnaireCtrl"> <div ng-repeat="(key,val) in questions | orderBy:key"> {{questions[key].question}} {{questions[key].answer}} </div>
<div ng-app="questionnaire">
<div ng-controller="QuestionnaireCtrl">
<div ng-repeat="(key,val) in questions | orderBy:key">
{{questions[key].question}}
{{questions[key].answer}}
</div>
</div>
</div>
(function(){
var app = angular.module('questionnaire',[]);
app.controller('QuestionnaireCtrl', function($scope){
$scope.questions = {
someItem: { question : 'First question' },
anotherItem: { question : 'Next question here' },
upgradeItem: { question : 'Another one' }
};
});
})();
现在,ng repeat可以正常工作,但以随机顺序显示问题。我尝试过使用orderBy
,但无法正常工作。我只希望问题和答案(当前不在数组中)按索引顺序(即它们在数组中的顺序)显示。或者,我可以向数组中添加另一个字段“section”,并按该顺序显示过滤后的字段。例如
$scope.questions = {
someItem: { question : 'First question', section : '1' },
anotherItem: { question : 'Next question here', section : '1' },
upgradeItem: { question : 'Another one', section : '2' }
};
这里的Fiddle示例:关于这个问题的AngularJS文档非常精确,并且适合您的具体用例。 将你的问题收集到一个对象中似乎是一件奇怪的事情。对象在属性中没有顺序,因此ngRepeat也不应该知道。相反,您可能希望将问题放入有序的数据结构(如数组)中 我在对象中的一个键字段上用orderBy表达式更新了fiddle JS: HTML:
不能依赖对象顺序,它没有定义。实际上,
orderBy
filter应该只用于数组。如果需要排序的输出,则应使用数组处理问题
:
$scope.questions = [
{
question: 'First question',
section: 'someItem'
},
{
question: 'Next question here',
section: 'anotherItem'
},
{
question: 'Another one',
section: 'upgradeItem'
}
];
而ngRepeat
变成:
<div ng-repeat="question in questions">{{question.question}} {{question.answer}}</div>
{{question.question}{{{question.answer}
演示:我为您的问题定制了一个过滤器 请查看您的更新 html: 还有另一个线程:
但是他使用命名属性。我只是花了很长时间查看Angular文档,无法让它为我工作,所以来到Stackoverflow。这不是一个答案,因此不要将其作为一个答案呈现。是像你这样的人破坏了这些社区,他们花时间在问题上挑刺,而不是提供有用的答案。好吧,我很抱歉。我会编辑我的回答。我刚注意到你改变了数组结构。数组中的每个索引都被命名,这似乎是导致问题的原因。这就是为什么我最初在repeat中使用key和value。删除数组名称不是一个选项。您是否可以编辑您的答案以适应?我似乎无法使您的解决方案使用正确的数组。像您这样使用对象将不允许您对输出进行排序。您应该使用数组,而不是对象。这可能会有帮助:
$scope.questions = [
{
question: 'First question',
section: 'someItem'
},
{
question: 'Next question here',
section: 'anotherItem'
},
{
question: 'Another one',
section: 'upgradeItem'
}
];
<div ng-repeat="question in questions">{{question.question}} {{question.answer}}</div>
<div ng-repeat="question in questions | orderByKey">
app.filter('orderByKey', [function () {
return function (input) {
if (!angular.isUndefined(input)) {
var tmpInput = [];
angular.forEach(input, function(value, key){
tmpInput.push(key);
});
tmpInput.sort();
var tmpOutput = [];
angular.forEach(tmpInput, function(key){
tmpOutput.push(input[key]);
});
return tmpOutput;
} else {
return input;
}
};