Search code examples
javascriptangularjsparse-platformangularjs-orderby

Parse + Angular orderBy Issue


I have an ng-repeat for a table in Angular. The data is coming from Parse.

    <tr dir-paginate="ticket in tickets | orderBy:sortType:sortReverse | itemsPerPage: 10">
        <td><input type="checkbox" class="checkthis" /></td>
        <td>{{ ticket.id }}</td>
        <td>${{ ticket.get("total").toFixed(2) }}</td>
        <td>${{ ticket.get("tax").toFixed(2) }}</td>
        <td>{{ ticket.get("paymentType") }}</td>
        <td>{{ ticket.createdAt | date: 'short' }}</td>
    </tr>

When I orderBy 'id' or 'createdAt' the sorting works properly. How do I go about ordering by total, tax or paymentType?


Solution

  • The parse objects' attributes are accessed via get(), and I think orderBy: filter depends on having a native getter.

    In angular therefore, one way to go is to create a service that extends the backbone object and provides native getters and setters:

    (function() {
        'use strict';
        angular.module('myApp.services').factory('MyClass', f);
    
        function f() {
    
            var MyClass = Parse.Object.extend("MyClass", {
                // instance methods
    
                // manually built getter like this
                attributeA : function() {
                    return this.get("attributeA");
                },
    
            }, {
                // class methods    
            });
    
            // or code-built getters/setters like this
            _.each(["attributeB", "attributeC"], function(p) {
                Object.defineProperty(MyClass.prototype, p, {
                    get: function() {return this.get(p);},
                    set: function(aValue) {this.set(p, aValue);}
                });
            });
            return MyClass;
        }
    })();
    

    This is probably good practice anyway, even if you don't need the attributes for orderBy. The service class is a good place to put promise-returning queries, for example.