How can I set the active class in EmberJS by binding to an array and a specific value?

I have an array called "mode" which contains values such as 'list', 'grid', and 'table'. I want to dynamically set the active li based on the active property.

mode: ['list', 'grid', 'table'], // dynamic values
active: 'list',

Here is the desired output:

<ul>
{{#each mode}}
    <li {{bind-attr class="?:active"}}>
        <a href="#">{{this}}</a>
    </li>
{{/each}}
</ul>

Can anyone advise on what should be placed in the bind-attr section so that when the 'active' property is set for any value in the 'mode' array, it will apply the 'active' class to the corresponding li?

Your assistance is greatly appreciated.

Answer №1

To create a child controller and add a computed property to determine if it is active, follow these steps:

The ul controller (Utilize the ApplicationController for simplicity):

App.ApplicationController = Ember.ObjectController.extend({
    mode: ['list', 'grid', 'table'],
    active: 'list'
});

The li controller:

App.LiController = Ember.ObjectController.extend({
    needs: ['application'],

    isActive: function() {
        return this.get('controllers.application.active') === this.get('model');
    }.property()
});

The template:

<ul>
    {{#each mode itemController="li"}}
    <li {{bind-attr class="isActive:active"}}>
        <a href="#">{{model}}</a>
    </li>
    {{/each}}
</ul>

JSBin

Why do I need an additional controller?

As stated in Ember's documentation, controllers allow you to enhance your models with display logic. Models will contain properties saved to the server, while controllers will include properties that are not required to be saved to the server.

Hence, the extra controller serves the sole purpose of holding the isActive property.

What is {{content}} used for?

content represents the underlying object of the controller, which in this case is a string literal. It is not a reserved keyword but rather a property of the controller.

I have revised my answer to utilize model instead of content. Both terms refer to the same thing, but it is recommended to use the model property consistently. For more insights, refer to this forum discussion.

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

Error occurred due to an abrupt termination of JSON input while transferring data through ajax communication

<script> $.ajax({ type: "POST", url: "http://localhost:3000/xot/us/confirm", crossDomain: true, dataType : 'json', contentType: "application/json; charset=utf-8", data:JSON.stringify({ username:"User" ...

What is the best way to adjust an element to match the height of the browser window?

I've coded a solution to ensure that the height of a section (#home) matches the height of the window, but it's causing issues. Here is the code snippet I used: // Adjust Home section height based on window height function fitHomeToScreen() { ...

In C, there are two distinct arrays that are cross-referencing each other

As a beginner in learning C / C++, I aim to create a program that counts the number of vowels, stored as vowCount, in a person's name provided as an input. My approach involves using two char arrays - name[20] to store the user input string and vowels ...

What is the best way to incorporate gl-matrix into a ReactJS application?

Recently, I dabbled in using ReactJS and decided to experiment with this project that involves importing JS modules like this: import Particle from './Particle' I wanted to switch the project to use gl-matrix for practice with the framework, bu ...

What is the best way to invoke a single ajax function across multiple pages with varying URLs?

Hello everyone! I am attempting to streamline my ajax post function and use it across the entire site with different URLs on each page. Below is my original function and how it currently operates: <button type="button" class="submit" ...

Implementing Google APIs with Next.js: Managing arrays without keys

Recently, I've started using next.js and came across the getStaticProps function. In this function, I'm loading data from a Google Sheet table into a constant. The result is an array of arrays, just like what the Google API returns shown below: [ ...

Can you explain the meaning of `suppressed_by_user` in Google One Tap?

When the user clicks sign in, I want the one tap to appear. The code below works fine when it runs as soon as the page loads. However, if I try to run it on click, I get the error suppressed_by_user. I do not have an ad blocking plugin enabled and I am uns ...

Styling HTML Select Box Options

My goal is to display the user's name and email within an option of a select box: <option>Adda <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="caabaeaeab8aafb2aba7baa6">[email protected]</a></option& ...

JavaScript - Load once

I have an issue with my JavaScript code where it loads data multiple times in a loop, causing long wait times. I need to figure out how to load the data only once. After researching the problem, I found some code that may help but I'm not sure how to ...

Delete an object from an array of ObjectIds using MongoDB update operation

How can I effectively remove an element from the orders array of my model named courier that contains ObjectIds of order models? Is there a way to achieve this without resorting to find, remove, and then save methods? (e.g. removing an order with a specif ...

In jQuery, turn off the hover function while the animation is in progress

I've implemented this jQuery animation: $('.menu1').stop().animate({left: "29%", top: '2%', width:'40%', fontSize: '60%'}, 3000); $('.menu2').stop().animate({left: "44%", top: &apo ...

How to iteratively process JSON array using JavaScript?

I am currently attempting to iterate through the JSON array provided below: { "id": "1", "msg": "hi", "tid": "2013-05-05 23:35", "fromWho": "<a href="/cdn-cgi/l/email-pro ...

The intersectObjects function is failing to retrieve the object from the OBJMTLLoader

Within my scene, I've introduced a new object along with several other cubes. To detect collisions, I'm utilizing the following code snippet that fires a Ray: var ray = new THREE.Raycaster(camera.position, vec); var intersects = ray.intersectObj ...

The drawing library (Google Maps) failed to load

I am looking to integrate drawing mode into Google Maps for my project. Below is the code snippet from my View: <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <me ...

Remove one specific file from test coverage

Can we direct jest to disregard a particular File from the test coverage report? I am not interested in utilizing the .skip function. ...

changing the time format with strtotime function in PHP

Seeking some assistance with a slightly basic question - currently, I'm implementing a counter using php and JS. The time is stored in an SQL time field within my DB, and upon fetching the time through a query, I now aim to convert it into an integer. ...

What is the reason behind getElementsByClassName not functioning while getElementById is working perfectly?

The initial code snippet is not functioning correctly DN.onkeyup = DN.onkeypress = function(){ var div = document.getElementById("DN").value document.document.getElementsByClassName("options-parameters-input").style.fontSize = div; } #one{ heigh ...

The mystery of the undefined Mongoose virtual array

Recently, I implemented a schema that looks like this: const FeedSchema = new Schema({ // ... posts: { type: [{ type: ObjectId, ref: 'post', }], }, }, { toObject: { getters: true, virtuals: true }, toJSON: { getter ...

Using PHP and jQuery to generate push notifications can result in issues with server performance

To simulate push notifications using PHP, I have implemented the following method: An AJAX call is made to a server-side script using jQuery. The script includes a for loop with a sleep function after each iteration to introduce delay. If a certain condi ...

Initiate a file download following the redirection of a user to a new page in NodeJS/Express

Overview I am currently developing a NodeJS project using Express. In the application, there are buttons visible to the public that trigger file downloads. These buttons are linked to protected routes which will redirect users to a login page if they are ...