Tips for assigning a class to a div based on the route in Angular

In my angular template, I have a basic ng-repeat with some div elements. Now, I am looking to add a class to a specific div if the $routeParams.userId matches the id of the object in the loop. You can refer to the second line of code below for clarification.

<div class="row" ng-repeat="contact in contacts">
    <div class="col-xs-12 contact-wrapper {{ if ($routeParams.userId == contact.id){ print 'active' } }}"> <!-- <== SOMETHING LIKE THIS -->
        {{ contact.user_name }}
        <br />{{ contact.last_pm_text }}
    </div>
</div>

Is there a way to assign the class active to the div when contact.id matches $routeParams.userId? Any suggestions or solutions would be greatly appreciated!

Answer №1

One way to achieve this is by utilizing the ng-class directive.

<div class="col-xs-12 contact-wrapper" ng-class="{'active' :  (userIdx == contact.id)}">

Additionally, ensure that in your controller, you retrieve the userId from the route parameters and assign it to a scope variable named userIdx. This is necessary because Angular does not allow the use of $routeParams directly within the HTML.

$scope.userIdx = $routeParams.userId;

According to the AngularJS documentation,

The ngClass directive enables the dynamic assignment of CSS classes to an HTML element by binding an expression that defines all the classes to be added

Answer №2

To achieve this effect, simply make use of ng-class:

https://docs.angularjs.org/api/ng/directive/ngClass

<div class="col-md-6 contact-container" ng-class="{'highlighted' : $routeParams.userID == contactID}"> 
        {{ contact.userName }}
        <br />{{ contact.latestMessage }}
</div>

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

What causes the error "property does not exist on type" when using object destructuring?

Why am I encountering an error in TypeScript when using Object destructuring? The JavaScript code executes without any issues, but TypeScript is showing errors. fn error: This expression is not callable. Not all elements of type '(() => void) | ...

What is the best way to add an insert button to every row?

Take a look at the image provided. When I click on any register button, the last row is being inserted instead of the desired row. What I'm aiming for is this: when I click register, the entire selected row should be stored in a separate table. Whe ...

React Animation Library With Smooth Initial Render and No Dependency on External Props

I'm currently implementing a Modal component within my app, utilizing Portals. My goal is for the Modal to smoothly fade in when it is rendered and fade out when it is no longer displayed. Upon examining the documentation for react-transition-group, ...

"Proper Installation of Angular Project Dependencies: A Step-by-Step

Whenever I clone an Angular project with older versions that are missing the node_modules folder, and then run npm install to install all necessary dependencies, I end up receiving numerous warnings and errors related to version mismatches. Here are some ...

"Utilize Node.js to generate a nested array structure with groupings

Here is an array data that I have: [ { tempId: 1, nik: '11002', employeeName: 'Selly Amaliatama', basic_salary: 3500000, id_component: 'AD0128114156', componentName: 'Tunjangan Maka ...

Redirecting and styling following an HTTP post operation

Implementing Stripe on my Firebase-hosted website. Utilizing a Cloud Function to handle the transaction. I have integrated the Stripe Checkout within a button displayed directly on my single HTML page, which then directs to the /charge function in inde ...

Default page featuring an AngularJS modal dialog displayed

I am attempting to display a modal popup dialog using an HTML template. However, instead of appearing as a popup dialog, the HTML code is being inserted into the default HTML page. I have included the controller used below. app.controller('sortFiles&a ...

POST data not being sent via AJAX

I am trying to use AJAX to submit form data to a PHP function, but it seems like the data is not being transmitted. Here is the code for the HTML Form: <form onSubmit="return registration();" id="registration_form"> <input type="email" id="e ...

The HTML file that was downloaded appears to contain jumbled and nonsensical text

I recently downloaded some HTML files from an Android application. They display perfectly when opened within the app, but appear jumbled on my computer. There is also a CSS file included. If necessary, I can provide the CSS file for reference. While I am n ...

Identify and mark labels when hovering over them

Hello everyone! I'm completely new to this, so please be gentle :). Apologies in advance if my terminology is off. I have zero experience with HTML, but I landed here from working with FileMaker. Currently, I am developing a FileMaker database for my ...

Is it possible to upload a file using Angular and ASP.NET Web API Core?

I am encountering an issue with CORS policy while making requests. It works fine when the content-type is set to 'application/json'. However, when I try to upload a file using content-type 'multipart/form-data', I receive an error: XML ...

Tips on using CSS to hide elements on a webpage with display:none

<div class="span9"> <span class="disabled">&lt;&lt; previous</span><span class="current numbers">1</span> <span class="numbers"><a href="/index/page:2">2</a></span> <span class="num ...

Activate automatic selection when the input field is disabled

How can I enable auto-select for text in an input field even when it is disabled? Currently, the auto select feature doesn't work when the field is disabled. Here is my HTML: <input type="text" class="form-control" ng-model="gameId" select-on-cli ...

Managing the file order within subdirectories for Rails assets

Utilizing rails to power a primarily single page application, I am incorporating angular as well. Within my assets/javascripts directory, I have organized folders for controllers, directives, filters, routes, services, and more. Certain elements, such as ...

Creating a dynamic visual experience with Angular 2: How to implement multiple font colors

I have a text area which is connected to one string, with the default text color set to white. <textarea style="background-color: black;color:#fff;" [(ngModel)]="outputText"></textarea> The connected string contains multiple variables. retur ...

After the initial submission, the Bootstrap placeholder for the Select Option is only displayed

I'm attempting to create a placeholder for my dropdown with multiple options using Angular and Bootstrap. However, it seems like I may be doing something incorrectly. I created an option for a placeholder such as please select and placed it at the top ...

The server encountered a "Cannot GET /socket.io" error while trying

I am experiencing an issue with my app that uses express/socket.io. The app is running smoothly without any errors, but when I make an http-request, I receive the following error message: GET http://xxxxxxx.com:3035/socket.io/1/?t=1449090610579 400 (Bad R ...

Utilizing dynamic variables in Angular Translate Rails: a tutorial

Has anyone encountered issues with passing variables from the gem angular-translate-rails to Rails? My setup consists of a backend in Rails and a front end in AngularJS. Here's what I've attempted so far: 1. Inside the controller: $translate(& ...

switch out asterisk on innerhtml using javascript

Is there a way to replace the asterisks with a blank ("") in the innerHTML using JavaScript? I've attempted this method: document.getElementById("lab").innerHTML = document.getElementById("lab").innerHTML.replace(/&#42;/g, ''); I also ...

Position the icon to the left side of the button using Bootstrap

Need help with centering text on a bootstrap 3 button while aligning the font awesome icon to the left side. <button type="button" class="btn btn-default btn-lg btn-block"> <i class="fa fa-home pull-left"></i> Home </button> Usi ...