AngularJS - 在NG-重复顺序不正确 [英] AngularJS - Incorrect order in ng-repeat

查看:109
本文介绍了AngularJS - 在NG-重复顺序不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的控制器定义如下CHAPS:

I have chaps defined in my controller like this:

  $scope.chaps =  [{"id":"1","chap_no":"1","name":"chap 1"},
                  {"id":"2","chap_no":"2","name":"chap 2"},
                  ...
                  {"id":"14","chap_no":"14","name":"chap 14"},
                  {"id":"15","chap_no":"15","name":"chap 15"}];

和中观,我有:

<li ng-repeat="ch in chaps | orderBy:'chap_no'">{{ch.name}}</li>

但我得到了错误的顺序(20 2后1 10后等)

but I'm getting the wrong order (10 after 1, 20 after 2, and so on)

chap 1, chap 10, chap 11, chap 12, chap 13, chap 14, chap 15, chap 2, chap 3, ...

这里的plunkr:<一href=\"http://plnkr.co/edit/Pc84ooB6dp2zoHXeawYn?p=$p$pview\">http://plnkr.co/edit/Pc84ooB6dp2zoHXeawYn?p=$p$pview

谁能告诉我,我做错了什么在这里

Can anyone tell me what I'm doing wrong here

推荐答案

chap_no 属性是一个字符串,因此其作为一个字符串命令。

Your chap_no property is a string so its ordered as a string.

您可以创建自定义过滤器这样的:

You can create a custom filter like:

app.filter('customSort',function(){
    function sort (a, b) {
        if (a > b) { return 1; }
        if (a < b) { return -1; }

        return 0;
    }

    return function(arrInput, prop) {
        var arr = arrInput.sort(function(a, b) {
            return sort(+a[prop], +b[prop]);
        });
        return arr;
    }
})

于是在你的HTML,你可以使用过滤器是这样的:

So then in your html you can use the filter like this:

<li ng-repeat="ch in chaps | customSort:'chap_no'" >{{ch.name}}</li>

例如: http://plnkr.co/edit/UWvinthK9r0zgRbHMCGd?p=preVIEW

这篇关于AngularJS - 在NG-重复顺序不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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