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 could be causing my token to not save after registering a user?

I am currently facing an issue when submitting a registration form. While the user is successfully created, the token is not stored in localStorage, which prevents me from being redirected immediately to the app and forces me to log in again. Here is my R ...

In JavaScript, the Else statement fails to run

Hi there, I'm currently working on creating a function to check the validity of a string input. This is what I have so far: function validatePassword(){ passW = prompt ("Enter Password:"); if (passW == 'Pass123'){ document.write ('Y ...

Steps for executing ASP code pulled from the database

In my ASP project, I have a single page where clicking on different links retrieves corresponding HTML from the database and loads it. Some links are always present on the page (static HTML), while other divs display dynamic content fetched from the DB. Wi ...

How to Build Two Navbars in BootstrapVue with a Sticky Bottom Navbar at the Top

My current project involves creating two navigation bars. The first navbar at the top consists of just a brand logo, while the second navbar at the bottom serves as the main navigation menu. I want the top navbar to scroll off the screen when users scroll ...

Enhance Bootstrap: adjust button width based on fluid text width

Incorporating Bootstrap 5 framework, I have designed a card that showcases brand information along with a navigation button on the right side. https://i.sstatic.net/25QVr.png When the description is brief, the button aligns perfectly in a single line. Ho ...

Error: The post request was blocked due to cross-origin restrictions

This is my unique script /** * Created by caneraydin on 16.03.2016. */ /** * Created by caneraydin on 16.03.2016. */ /** * Created by caneraydin on 16.03.2016. */ /** * Created by caneraydin on 16.03.2016. */ var app=angular.module('todoApp ...

The website doesn't give my codes enough time to execute fully

I have a series of commands that I need to execute: Retrieve cookie from the browser using the JS Cookie plugin in mypage.php Validate its value with Ajax and my PHP scripts in myapi.php Set certain SESSION variables in myapi.php Utilize the values store ...

Having trouble with krakenjs angularjs $http's delete method not functioning as expected

While using KrakenJs, I came across a workaround to send POST/PUT/DELETE requests without disabling "csrf" by including a "_csrf" parameter in the body In my index.dust file: <input id="csrfid" type="hidden" name="_csrf" value="{_csrf}"> In myScri ...

Having trouble with $addToSet and $push not working in updates using Mongoose with MongoDB in Node.js?

My issue involves Mongoose as I am attempting to update a document in MongoDB using the mongoose module. Below is my schema: var User = new mongoose.Schema({ name: String, email: String, list_houses: [{ id_house: S ...

An HTML button generated by a .js file is able to execute a .js function without any issues, but it inadvertently removes all .css styling

Currently grappling with an issue in my JavaScript self-teaching journey that I can't seem to resolve or find examples for. The problem at hand: When the HTML button calls a .js function, it successfully executes the function but also wipes out all C ...

An unexpected error occurred while parsing the JSON document: "unexpected token: '{'"

I'm facing an issue where I need to specify a URL in a JavaScript app that retrieves weather data from an API. The URL is constructed using a string and some variables. When I initially wrote the code below, I encountered the error message Missing { b ...

"Utilizing a Font Awesome icon within the dropdown list of a combobox in Ext JS

I have attempted multiple methods to add an icon in the displayfield when a combo box item is selected without success. Here is the fiddle link for anyone who would like to help me with this issue. Your assistance is greatly appreciated. View the example ...

Experimenting with creating collapsible panels using Bootstrap/CSS can result in various outcomes

, I am in the process of constructing a collapsible sliding left panel using bootstrap 5. The progress has been notable, but I am encountering some hurdles. Upon reviewing the code at this link: https://jsfiddle.net/dizzy0ny/86wjas9L/108/, you will witness ...

How can I customize the styling of an SVG pseudo element using Font Awesome 5?

I've implemented font awesome 5 pseudo elements to attach an :after tag to my element as shown below: &:after { content: "\f068"; font-weight:400; color:$brandRed; float:right; font-family: "Font Awesome 5 Pro"; } The c ...

Issue encountered while retrieving values from JSON for the data table

I recently developed an application using a combination of React and Flask to display JSON data in a table format. While I can successfully see the data loaded in the console, I encountered difficulties in rendering it within the data table. The technologi ...

Utilizing Angular to Handle Undefined Variables in String Interpolation

Seeking a way to showcase data obtained from an external API on a webpage using Angular's string interpolation. If no data is retrieved or is still pending, the aim is to display 'N/A'. An attempt was made following this method, but encoun ...

Updating an Object in vue.js Upon Click Event to Add a New Value

I currently have a code snippet that looks like the following: arr = [ { val1: a, val2: b }, { val1: a, val2: b }, { val1: a, val2: b } ] <div v-for="single in arr"> <button v-on:click="addSome"></button> </div> When I c ...

Tips for effectively utilizing the count() function within selenium's xpath feature?

By utilizing the count() function within XPath, we can extract the total count of matching nodes instead of using findElements() and size() methods. Do you know if the count function in XPath returns an integer value? For example, Let's say my xpath ...

Is jQuery failing to respond after being transferred from HTML to PHP?

The debug message from the Venkman debugger reads as follows: $("#aboutbox") is null [Break On This Error] $("#aboutbox").hide(); I'm at a loss on how to resolve this issue! It was functioning perfectly in HTML: But after transitioning it to PH ...

Leveraging HTML5 file uploads alongside AJAX and jQuery

While there are questions with similar themes on Stack Overflow, none seem to quite fit the bill for what I am looking for. Here's my goal: Upload an entire form of data, including a single file Utilize Codeigniter's file upload library So fa ...