AngularJS排序依据数组索引 [英] AngularJS orderBy array index

查看:1096
本文介绍了AngularJS排序依据数组索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NG重复,看起来像这样:

I have an ng-repeat that looks like this:

<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>

控制器看起来是这样的:

The controller looks like this:

(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-重复工作正常,但显示在一个随机的顺序问题。我已经使用排序依据,但不能得到它的工作尝试。我只是想的问题和答案(目前是不是在数组中)在指数的顺序(即它们在数组中是顺序)来显示。我也可以另一个字段部分的添加到阵列中,并显示它们的顺序过滤。例如。

Now the ng-repeat works fine but displays the questions in a random order. I've tried using orderBy but can't get it working. I just want the questions and answers (which aren't currently in the array) to display in order of index (i.e. the order they're in the array). Alternatively I could add another field 'section' to the array and display them filtered in that order. E.g.

$scope.questions = {
  someItem: { question : 'First question', section : '1' },
  anotherItem: { question : 'Next question here', section : '1' },
  upgradeItem: { question : 'Another one', section : '2' }
};

在这里小提琴例如: http://jsfiddle.net/k52ez/

推荐答案

您可以不依赖对象的订单,它没有定义。事实上,排序依据过滤器应该只阵列工作。如果你需要有序输出,你应该使用问题数组:

You cannot rely on object order, its not defined. In fact, orderBy filter is supposed to work with arrays only. If you need sorted output you should use array for questions:

$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>

这篇关于AngularJS排序依据数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆