Sorting repeaters alphabetically in Polymer

Using Angular JS, you can sort a repeater using a filter in the following way:

<li ng-repeat="link.title for link in links | orderBy:'title'">

Now, I'm delving into experimenting with Polymer and wondering if it's possible to achieve something similar using a Polymer filter. My goal is to declaratively sort data within the markup without directly manipulating the dataset. So, I've attempted something like this (simplified code 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 encountered an issue where the sort function in the element prototype receives an empty array (despite having objects in the links array).

Additionally, here is the response from the AJAX call I'm making:

{
"data" : [
    {
        "name" : "github",
        "url" : "..."
    },
    {
        "name" : "linked",
        "url" : "..."
    },
    {
        "name" : "stack",
        "url" : "..."
    },
    {
        "name" : "gplus",
        "url" : "..."
    },
    {
        "name" : "twitter",
        "url" : "..."
    }
]
}

Am I on the right track or is this a sign that I should call it a night?

Thanks in advance

Answer №1

When using the sort filter, it will be given the links array as an argument. You should structure your code 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;
}

Initially, the filter is likely to be called with an empty array because the links array starts off that way and gets populated asynchronously.

To mimic Angular's approach more closely, you can consider the following:

<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);
}

While there are various ways to refactor the sorter for reusability, one easy solution is to use the polymer-filters library. This library offers the orderBy filter (and many others) that closely resembles Angular's functionality. By leveraging polymer-filters, you can follow a similar syntax as demonstrated in the second example while skipping the need to implement orderBy on your own.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is the image cut in half on mobile devices but displaying correctly on computer screens? Could it be an issue with

There seems to be an issue on mobile screens that does not occur on computer screens. When the user clicks on the image, it disappears, and when they click another button, it reappears. However, there is a problem with how the image appears - it is cut off ...

"Make updates to the data with the help of a button input

I am working on a form that has two input type buttons. The first button is labeled "edit", and when clicked, it enables the input field. The second button is labeled "save", and when clicked, it disables the input field and should save the new values in a ...

Complete guide on updating table styles by implementing a dark mode toggle button

I recently implemented a dark mode toggle button in my project after watching a tutorial on YouTube. Here is the HTML code for it: <div class="dark-div"> <input type="checkbox" class="checkbox" id="chk" ...

Can Vue.js accommodate nesting a v-model within an array?

How can I implement filtering on groups within a Vue app using a nested array with v-model? I attempted to achieve this using the following template... <div id="app"> <div class="filter__control filter__control--tags"> <div class="fi ...

What causes JavaScript Date to not update correctly during daylight savings time changes?

The Enigma of JS Dates My Initial Expectations In my Node applications, I have implemented functionality to send broadcasts to platforms like Facebook Messenger. Users subscribe to receive these broadcasts at a specific time, for example, 2pm daily. Whe ...

JQuery Mobile: Adding fresh, dynamic content - CSS fails to take effect

I've encountered this issue before, but I'm still struggling to resolve it. When adding dynamic content to a page (specifically a list-view), the CSS seems to disappear once the content is added. I've tried using the trigger("create") functi ...

Leveraging PHP to retrieve the file path for integration with JavaScript

I am working on a project where I need to retrieve data from an unknown number of .json files and display it on a webpage. To accomplish this, I have written code that loops through a PHP array containing file directory information on the server to dynamic ...

Incorporate JavaScript to dynamically fetch image filenames from a directory and store them in an array

By clicking a button, retrieve the names of images from a folder and store them in an array using jQuery. I currently have a script that adds images to the body. In the directory images2, there are 20 images stored. The folder images2 is located in my i ...

Searching for a specific collection item based on a custom property (excluding _id) in Meteor - what's the best approach?

I am facing an issue with my application that utilizes Flow Router along with its pub/sub functionality. I have set up a collection and template helpers. The code works fine on the client side. Template.theCase.helpers({ theCase: function () { ...

Revamping the Jquery Waypoint

Greetings, I am currently delving into the world of Jquery waypoints and facing a bit of challenge getting it to work. My goal is to have an "alert" pop up once an element becomes visible on the screen, but for some reason, the alert doesn't show up w ...

Tips for concealing a component in the DOM using ng-if in angular.js and angularmaterial:

Currently, I'm utilizing angular.js 1.5 along with angular material on the frontend to populate the DOM with objects retrieved from the Database. Within one of the repeaters, I am facing an issue where I need to determine if an object is already prese ...

What is the best way to capture source code and store it in a text file?

Can you assist me in extracting the source code of a webpage and saving it into a text file? My goal: Instead of going through the process of right-clicking on the page, selecting view source code, copying, and pasting into a text file... I want to simpl ...

What is the best way to create shapes in Three.js using the mouse?

I'm searching for a way to enable users to draw their own cube, similar to the example here (try drawing a cube on a grid): Screenshot: Shapesmith has efficiently solved this using Three.js, but it relies on Backbone.js. I'm wondering if it&apo ...

module-deps is unable to resolve relative require statements

Attempting to navigate the dependency graph of a Node.js file using module-deps has presented a challenge. Below is a mostly minimal testcase: var resolve = require('resolve'), mdeps = require('module-deps'), builtins = require ...

Retrieving a specific object from a subarray using MongoDB's ID

My MongoDB document includes the following: const Categories = [ { _id: 's654fs54s6d4f' title: 'category 1', SubCats: [ { _id: 'jhgfsf68746' name: 'subcat 1', i ...

I'm getting an error message that says THREE is not recognized. How can I resolve this issue

Currently, I am diving into the world of Three.js and encountering a persistent error that has been quite challenging to resolve. Despite my efforts in exploring various solutions, the error remains unresolved. I have ensured that the Three.js library is ...

How to incorporate Base64 textures into Three.js

I am currently trying to load textures from URLs, but since my backend code is generating planets, I need to display them using Base64 instead. I'm experimenting with procedural generation, so I'd rather not save the image and then load it via U ...

Converting a JavaScript array to formData

Struggling with sending an array via Ajax to PHP. For more information, visit jsfiddle https://jsfiddle.net/CraigDavison/9spyn7ah/ function autoPopulate() { var cast = "John Wayne, Julia Roberts, Kevin Spacey"; cast = cast.split(', '); ...

Bootstrap modal for interactive table rows

I'm working with a 3-rowed table and I want to be able to click on each row and display more information about the content in a modal pop-up. However, when I attempt to click on a row, the screen darkens but the pop-up does not appear. <!DOCTYPE h ...

Converting an object to an array and assigning the values to a select field in Sencha

My issue lies in setting the selectfield for England, which I am retrieving from the server. Despite being able to set textfields like this: Ext.getCmp('email').setValue(email); Why doesn't this work for selectfields? I am relatively new ...