Orderby not working with dict syntax on ng-repeat

前端 未结 6 1976
谎友^
谎友^ 2020-12-06 03:53

I am trying to use ng-repeat with a dictionary style syntax and apply an order to the key value.

(key, value) in something | orderBy:\'key\'

It

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-06 04:45

    Instead of using orderby filter which only supports arrays and not objects. You can write your own filter like this I took the code from Justin Klemm http://justinklemm.com/angularjs-filter-ordering-objects-ngrepeat/ and added support for specifying multiple ordering fields. The filter example below is to filter based on properties in the values but you can easily change it to filter based on the key as well.

    app.filter('orderObjectBy', function()
    {
        return function(items, fields, reverse)
        {
            var filtered = [];
            angular.forEach(items, function(item)
            {
                filtered.push(item);
            });
    
            filtered.sort(function (a, b)
            {
                var result = 0;
    
                for (var i = 0; i < fields.length; ++i)
                {
                    if (a[fields[i]] > b[fields[i]])
                    {
                        result = 1;
                        break;
                    }
                    else if (a[fields[i]] < b[fields[i]])
                    {
                        result = -1;
                        break;
                    }
                }
    
                return result;
            });
    
            if (reverse)
            {
                filtered.reverse();
            }
    
            return filtered;
        };
    });
    

    Then inside your html5 web page use it like so where statistics is a map/dictionary with key value pairs.

    {{stat.Name}}
    {{stat.NumTimesPartnered}}
    {{stat.NumTimesOpponent}}

提交回复
热议问题