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

Feathers.js - Incorporating Static Content

Recently, I've been exploring the capabilities of feathers.js for a new project and have been quite impressed with its potential. Intrigued by what it offers, I decided to embark on creating a basic content management system as a way to further my lea ...

What could be the reason for the defaultCommandTimeout not functioning as expected in my script

Is there a way to wait for only one particular element in Cypress without having to add wait commands everywhere in the test framework? I've come across the solution of adding defaultCommandTimeout in the cypress.json file, but I don't want it t ...

Concurrent HTTP Requests - AngularJS

My directive, known as machineForm, includes a dataService: dataService.getMachineTaxesById($scope.machineId).then(function (response) { $scope.machine.machineTaxes = response.data; }); I am using this directive twice simultaneously. <div class= ...

Is there a way to retrieve the objects generated by DirectionsRenderer on Google Maps V3?

Is there a simple method to access the objects and properties of the markers and infowindows that are generated by the DirectionsRenderer? (such as the "A" and "B" endpoints of the route) I want to swap out the infowindows for the "A" & "B" markers wi ...

Avoiding Memory Leaks and Managing JS Heap Size While Polling Large Amounts of Data Every 5 Seconds with Vuex

I'm currently working on a Vue application that utilizes Vuex for state management. Within this application, I have several store modules set up at the root level. Periodically, every 5 seconds, I retrieve a large amount of data and update the store s ...

Issues with broadcasting in React using Socket IO have arisen

Currently, I am developing a game using Socket IO where each room has its own channel of communication. The issue I am facing is that when a player places a bet, not only does the opponent receive the message, but the player themselves also receives it. B ...

Issue with Node.js and Express redirect not directing to intended URL

Utilizing the nodejs/express view engine in my application allows me to render an assigned template onto the screen when the route points to an existent URL. Previously, I had set up a redirect to the homepage for any user typing in an unexisting URL. Howe ...

What is the best way to link a newly created contact to the current user in Mongoose?

I'm faced with the challenge of creating a contact that is specifically added to the current user's contact array. Currently, my controller only creates a generic contact and doesn't cater to the individual user. Controller: function cont ...

I found myself pondering the significance of the {blogs: blogs} in my code

app.get("/articles", function(req, res){ Article.find({}, function(err, articles){ if(err){ console.log("an error occurred!!!"); }else{ res.render("homepage", `{articles: articles}`); } }); I created this c ...

Retrieving the Short Date Format from the user's device or browser within a React application

Currently, I am in the process of utilizing reactjs along with material UI datepicker. My objective is to transmit the short date format to the datepicker component, such as format="MM/dd/yyyy". In addition, I wish to employ the pre-existing date ...

Having trouble with the functionality of the AngularJS Custom Service?

I have developed a straightforward service as shown below: var app = angular.module('myApp', ['ngRoute']); app.service('UserService', function() { this.user = {firstName:"",middleName:"",lastName:"",email:"",dob:""}; this.ad ...

Unpredictable Redirection when URL is Clicked using PHP or Javascript

Looking to send users to a random URL from a specific list? For instance: With 3 URLs available - Google.com, Facebook.com, and Yahoo.com <a href="<?php $sites[array_rand($sites)] ?>">Click here</a> Upon clicking the link, users will ...

What is causing the issue with mongoose populate not working when trying to populate an array?

My database setup includes 2 schemas: const mongoose = require('mongoose'); const PinSchema = new mongoose.Schema({ title: String, content: String, image: String, latitude: Number, longitude: Number, author: { type: mongoose.Sch ...

troubleshoot clientWidth not updating when CSS changes are made

Summary: When I adjust the size of a DOM element using CSS, its directive fails to acknowledge this change even with a watch on the size. Aim I have multiple custom directives (simple-graph) each containing an svg. My goal is to enlarge the one under the ...

A JavaScript function to separate a URL and eliminate the final segment

http://www.google.com/site!#656126.72367 Is there a way to split and remove the part after the exclamation mark in this URL using JavaScript when the page is loaded? I am looking to achieve http://www.google.com/site ...

What could be causing the d3.js pie chart transition to malfunction?

Today I am experimenting with d3.js to create a unique pie chart from scratch. While following tutorials here as my base, there were modifications made in the code to add personal touches and customization. The challenge arose during Step 6 when introduc ...

The versions of my npm and node are not compatible, despite using nvm

I have recently started working with node and npm. I need to run a program repository for my job, which requires compatibility with node version 10.13.0 or even 8.11. I attempted to install nvm, but now every time I try to execute any npm command (includ ...

Angular 4's Panel Window: A User-Friendly Interface

Having experience with Adobe Flex, I am familiar with creating new panel windows in Action Script by using the 'new' keyword and popping them up using popups. The customization of these windows was achieved through functions provided in the Panel ...

How can you turn consecutive if statements into asynchronous functions in JavaScript?

In my code, I have a loop with a series of if statements structured like this: for( var i = 0; i < results_list.length; i++){ find = await results_list[i]; //result 1 if (find.Process == "one") { await stored_proc(38, find.Num, find ...

Sending STATIC_URL to Javascript file in Django

What is the most effective method for transferring {{ STATIC_URL }} to JavaScript files? I am currently using django with python. Thank you in advance. Best regards. ...