Coo*_*oop 5 html javascript arrays angularjs
我有一个ng-repeat,看起来像这样:
<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>
Run Code Online (Sandbox Code Playgroud)
控制器看起来像这样:
(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' }
};
});
})();
Run Code Online (Sandbox Code Playgroud)
现在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' }
};
Run Code Online (Sandbox Code Playgroud)
这里的小提琴示例:http://jsfiddle.net/k52ez/
您不能依赖对象顺序,它没有定义。事实上,orderBy过滤器应该只适用于数组。如果您需要排序输出,您应该使用数组questions:
$scope.questions = [
{
question: 'First question',
section: 'someItem'
},
{
question: 'Next question here',
section: 'anotherItem'
},
{
question: 'Another one',
section: 'upgradeItem'
}
];
Run Code Online (Sandbox Code Playgroud)
并ngRepeat变为:
<div ng-repeat="question in questions">{{question.question}} {{question.answer}}</div>
Run Code Online (Sandbox Code Playgroud)