Navigating through Index in #each in emberjs

Take a look at the code provided below:

http://jsbin.com/atuBaXE/2/

I am attempting to access the index using {{@index}}, but it doesn't seem to be compiling. I believe that handlebars should support this feature:

{{#each item in model}}
  {{@index}} 
  {{item}}
{{/each}}

The above code is not working as expected for me. I am unsure whether {{@index}} is actually supported or not.

The versions currently being used are:

  • Ember.VERSION : 1.0.0
  • Handlebars.VERSION : 1.0.0

Answer №1

UPDATE

Exciting news! With this latest PR, the each helper in Ember now supports indexing using the new block params syntax. This feature is currently available on canary and is expected to be enabled by default in ember 1.11

{{#each model as |item index|}}
  <li>
    Index: {{index}} Content: {{item}}
  </li>
{{/each}}

Check out a live sample here

FOR PREVIOUS VERSIONS

If you're working with an older version, you can still achieve similar functionality using {{_view.contentIndex}}.

{{#each item in model}}
  <li>
    Index: {{_view.contentIndex}} Content: {{item}}
  </li>
{{/each}}

Take a look at an example in action here

Answer №2

In the Ember Handlebars version, this feature does not exist. However, one workaround is to use an item controller and include a property that specifies if it's the first or last item.

App.IndexController = Ember.ArrayController.extend({
  itemController: 'itemer'
});

App.ItemerController = Ember.ObjectController.extend({
  needs:['index'],
  isFirst: function(){
    return this.get('color') === this.get('controllers.index.firstObject.color');
  }.property('controllers.index.firstObject')
});

Answer №4

One interesting approach, highlighted by @kingpin2k, is to follow The Ember Way by using a controller to enhance a model. Specifically, adding an index property to signify its position in the collection.

My personal twist on this method involves creating a dedicated set of instance controllers tailored for the specific task:

App.PostsIndexController = Ember.ArrayController.extend({
  indexedContent: function() {
    get('content').map(function(item, index) {
      App.PostsItemController.create({
        content: item,
        index: index
      });
    });
  }.property('content')
});

App.PostsItemController = Ember.ObjectController.extend({
  index: null
});

Answer №5

If you want to show the index value in your view as 1-indexed, another option to consider is using CSS Counters. These are supported even on older browsers like IE 8.

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

Bing Translator and XMLHttpRequest are two powerful tools for translating and

When running the code snippet below, I encounter an issue where I am not receiving status 200 and responseText. However, when using the following URL: http://api.microsofttranslator.com/V2/Http.svc/GetLanguagesForTranslate?appId=F1B50AB0743B541AA8C070890 ...

Using the KnockOut js script tag does not result in proper application of data binding

Being new to knockout js, I found that the official documentation lacked a complete html file example. This led me to write my own script tags, which initially resulted in unexpected behavior of my html markups. Strangely enough, simply rearranging the pos ...

Issue with MUI toggle switch not updating display and value upon clicking once

I'm currently experiencing issues with a Material UI toggle switch in my project. Initially, when the component loads, the console log displays the correct value. However, when I toggle the switch from 'yes' to 'no', the visual cha ...

jQuery ajaxSetup: handling error retries for ajax calls is not possible

When using $.ajaxSetup(), I am faced with the challenge of making an AJAX request after refreshing a valid token in case the previous token has expired. The issue arises when attempting to execute $.ajax(this) within the error callback. $.ajax({ url: ...

Contrasting methods of adding a value to an array state in React

Can you advise me on the most effective method for inserting a value into an array, as well as explain the distinctions between these two code examples? setOtoValue((current) => [ ...current, Buffer.from(arraybuf, 'binary').toString(' ...

Unable to refresh HTML table using Vuex data in Vue JS

I am new to working with Vue.js and particularly Nuxt. I am facing an issue with updating a table using data fetched from the backend. Even though I can see the data in the Vuex tab when the page loads, I cannot seem to populate the table with it. The func ...

What is the best way to synchronize CouchDB with multiple PouchDB instances in an AngularJS application?

I need help with my Angular project. I'm trying to figure out how to sync multiple PouchDB databases to a single CouchDB instance without losing any data. Can anyone provide some guidance or advice? ...

Encountering difficulties with image processing on a web page

Recently, I've been experimenting with uploading an image and converting it to a grayscale version on my webpage. Oddly enough, the javascript code works perfectly when tested locally but fails to generate the grayscale image once integrated onto the ...

What's the best way to determine which of the two forms has been submitted in Django?

On my homepage, I have both a log_in and sign_up form. Initially, the log_in form is displayed by default, but when a user clicks on the Sign Up button, the sign_up form appears. These toggles switch depending on which button the user clicks. from django ...

Browser-based Javascript code execution

I've been pondering this question for a while now, and I can't seem to shake it off. I'm curious about how JavaScript is actually processed and executed in a web browser, especially during event handling scenarios. For instance, if there are ...

What could be causing the appearance of a Firefox error message during the execution of a Protractor test?

Currently, I am conducting end-to-end testing on an AngularJS application using Protractor. Every time I execute a spec, Firefox launches and closes with a particular message appearing: After that, Firefox starts working properly and the specs run smooth ...

Signing off from GitHub Packages for npm

As I work on a project that utilizes a private GitHub package, I have been using it locally with the command npm login --registry=https://npm.pkg.github.com. However, this approach has posed problems when attempting to deploy the project in a production en ...

Tell me the permissions that a user possesses in discord.js

I need help creating a command using Discord.js that can display a user's permissions. For instance, the command could be $permissions @user and it should output something like: "User permissions within this guild: " I'm unsure if ...

How can I display an array of data with a changing name using a FlatList in React Native?

How can I render a list of array data with a dynamic name in a FlatList using React Native? Below is the list of data that I would like to display in the FlatList: const movies = [ { '4W2JJ0CLbvfLJzBUHORVaz6sAGv2': [ { name: ...

Tips for enabling browser back and forward functionality in a one-page website design

Building on the previous discussion about optimizing a horizontal sliding layout (Most efficient way to do a horizontal sliding layout), I'm curious if it's feasible to enable the back and forward buttons in the browser when implementing a single ...

Ways to enlarge a YouTube thumbnail upon loading using JavaScript

I recently found a solution to my question on how to prevent YouTube videos from repeating even when different embedded codes are used. I have a specific need to resize the thumbnail image of my YouTube video to width:146px and height:124px when the page l ...

Implementing Enter key functionality to add items to a Todo list using pure DOM manipulation

var listLis=document.getElementById('list'); const addbutton=document.querySelector('.fa-plus') const inputBar=document.querySelector('.show') function showInput(e){ inputBar.classList.toggle('show') } addbutt ...

Obtaining various values for checkboxes using dynamic data in a React application

Retrieve all checkbox values dynamically import * as React from "react"; import Checkbox from "@mui/material/Checkbox"; import FormControlLabel from "@mui/material/FormControlLabel"; import axios from "axios"; expor ...

Troubles arising while using ng serve in Angular 2

I'm currently facing an issue during the installation process of an existing Angular application. When trying to run the application using the ng serve command, I encounter the following error message: The "@angular/compiler-cli" package was not prope ...

Focus on input using jQuery (fixed focus)

How can I ensure that my input always has value and the focus remains fixed on it until values are typed, preventing the cursor from escaping the input field? While I know the existence of the focus() function, how can I effectively utilize it as an event ...