alphabetical sorting of repeater in Polymer
javascript, polymer
Solution
The `sort` filter is going to receive the `links` array as an argument, so you need to do something like this:
sort: function(items) {
items.sort(function (a, b) {
var titleA = a.title.toLowerCase(), titleB = b.title.toLowerCase();
if (titleA < titleB) return -1;
if (titleA > titleB) return 1;
return 0;
});
return items;
}
It's likely to be called once with the empty array, because `links` starts out that way and is populated asynchronously.
To get closer to the Angular construction, you could have something like this:
<template repeat="{{link in links | orderBy('title')}}">
...
orderBy: function(items, key) {
var sorter = function (a, b) {
var titleA = a[key].toLowerCase(), titleB = b[key].toLowerCase();
if (titleA < titleB) return -1;
if (titleA > titleB) return 1;
return 0;
};
items.sort(sorter);
}
There are lots of ways to extract `sorter` into a reusable form, but the simplest solution is to import polymer-filters which will provide `orderBy` (and lots of other filters) that should be the same or similar to Angular's. Using polymer-filters, the syntax is the same as I've shown in the second example, but you can completely omit the `orderBy` implementation.
Problem
In angular Js you sort a repeater using a filter, like this: ``` <li ng-repeat="link.title for link in links | orderBy:'title'"> ``` I am experimenting with polymer and i wondered in you could do similar using a polymer filter (i want to sort the data declaratively in the markup not directly on the dataset). So i've been trying to something along the lines of this (i've stripped down the code a bit for clarity): ``` <polymer-element name="image-links" attributes="axis data width"> <template> <core-ajax id="ajax" auto url="../data/{{data}}.json" on-core-response="{{linksLoaded}}" handleAs="json"> </core-ajax> <ul> <template repeat="{{link in links | sort}}"> <li>...</li> </template> </ul> </template> <script> Polymer('image-links', { links: [], linksLoaded: function () { this.links = this.$.ajax.response.data; }, sort : function (a, b) { var titleA = a.title.toLowerCase(), titleB = b.title.toLowerCase(); if (titleA < titleB) return -1; if (titleA > titleB) return 1; return 0; } }); </script> ``` i get an empty array passed to the sort function in the element prototype (there are definitely objects in the links array). also here is the response from the ajax call i'm using: ``` { "data" : [ { "name" : "github", "url" : "..." }, { "name" : "linked", "url" : "..." }, { "name" : "stack", "url" : "..." }, { "name" : "gplus", "url" : "..." }, { "name" : "twitter", "url" : "..." } ] } ``` Is this the right way to be approaching this or is it way past my bedtime?! Thanks in advance