How to emphasize the anchor tag chosen within Angularjs by utilizing ng-repeat

After gathering some data, I have successfully bound it to anchor tags using ng-repeat.

<table style="width: 60%">
                <tr>
                    <td style="text-align: center" ng-repeat="displayyears in displayYears">
                        <div>
                            <a href="javascript:void(0)" style="padding: 30px,30px,30px,30px; font-size: 18px" ng-class="StyleOfYear" ng-click="selectedYear(displayyears,this)">{{displayyears}}</a>
                        </div>
                    </td>
                </tr>
            </table>

Here is the CSS code

<style>
    .slectedYear {
        background-color: red;
    }

    .loadYear {
        background-color: none;
    }
</style>

  • I'm currently facing an issue where all anchor tags change their background color when clicked. Here's what I've tried:

Javascript code snippet

//Controller 
 $scope.StyleOfYear = "loadYear";
  $scope.selectedYear = function (value, context) {
            context.$parent.StyleOfYear = "slectedYear";
            $scope.selectedYearValue = value;
        }

Unfortunately, my current implementation changes the background color of all anchor tags instead of just the selected one.


My code currently selects all anchor tags when I click on a specific year like 2015.


However, I would like to specifically change the background color of the anchor tag corresponding to 2015 only when it is clicked, keeping all other anchor tag backgrounds non-colored.

This is how I envision the outcome:


I am attempting to implement a menu highlighting feature for active items using ng-repeat, but I am unsure about the best way to achieve this.

Answer №1

Consider adjusting your approach for better results. Utilize a service to manage the years and include a 'selected' attribute in the returned year object.

Utilize ng-repeat to loop through these objects, determining and displaying colors based on the attribute value for each item within ng-repeat.

Your selectedYear function can be housed within the service, simply toggling the designated object with selected=true. The data bindings will handle the rest.

There are various methods to achieve this depending on your code's syntax and structure, but the following example could potentially work (though untested):

var module = angular.module('myapp', []);

module.service('yearService', function(){
    this.years = [
        { 'display': '2012', 'selected': false },
        { 'display': '2013', 'selected': false },
        { 'display': '2014', 'selected': false },
        { 'display': '2015', 'selected': true },
        { 'display': '2016', 'selected': false },
        { 'display': '2017', 'selected': false },
        { 'display': '2018', 'selected': false }
    ];
    this.selectYear = function selectYear(year) {
        // iterate through the years and set only the 
        // selected one to true, others to false
    };
});

Be sure to inject the service into your controller and assign it to scope (e.g., as yearService, and

<table style="width: 60%">
    <tr>
        <td style="text-align: center" ng-repeat="year in yearService.years">
            <div>
                <a href="#" class="year" ng-class="{year.selected: slectedYear}" ng-click="yearService.selectYear(year)">{{year.display}}</a>
            </div>
        </td>
    </tr>
</table>

Note that I assumed a base CSS class of .year instead of using the style tag, while incorporating your existing .slectedYear class.

Your HTML also warrants revision - please eliminate the table!

EDIT: I neglected to add the dynamic class - rectified now.

Answer №2

I received this information from @Sam

In order to apply a style conditionally, I utilized ng-class

Modification in HTML:

<a href="javascript:void(0)" style="padding: 30px,30px,30px,30px; 
 font-size: 18px" **ng-class="{slectedYear: displayyears==selectedYearValue}"** 
 ng-click="selectedYear(displayyears,this)">{{displayyears}}</a>

Styling section:

<style>
    .slectedYear {
        background-color: red;
    }

    .loadYear {
        background-color: none;
    }
</style>

Javascript code:

$scope.selectedYear = function (value, context) {
            $scope.selectedYearValue = value;
        }

I implemented a simple condition where if the displayed year matches the selected year, it assigns the slectedYear class

Solution:

The following code successfully resolved my issue

ng-class="{slectedYear: displayyears==selectedYearValue}

Thank you.

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

I am encountering an error with an Unhandled Promise Rejection, but I am unable to determine the reason behind it

const express = require('express'); const cors = require('cors'); const massive = require('massive'); const bodyParser = require('body-parser'); const config = require('../config'); const app = express(); ...

How to change the color of a row in Jquery selectize using its unique identifier

Is it possible to assign different row colors for each value in the jquery selectize plugin? I would like to set the row color to green if the ID is 1 and red if the ID is 0. This is my selectized field: var $select = $('#create_site').selecti ...

Utilizing modal functionality in CakePHP 3 (or: Incorporating JavaScript within Controllers)

I have a typical form that was created using cake/bake. After the form is submitted, my controller checks a simple condition: If condition A is met, it will just save the data using patchEntity($foo, $this->request->getData()) If condition B is me ...

Ways to rouse a dormant AudioTracks feature

When I click a button, I am able to get the correct value of AudioTracks.length. However, without clicking the button, I am unable to retrieve this value. Take a look at my code below. It works at line (B) but not at (A). Can you help me understand why and ...

Struggling to retrieve the data from my table (getElementById function is malfunctioning)

I am attempting to retrieve a line from a dynamic table once the "reserve" button is clicked (or the line itself is clicked if that is important), but the 'getElementById' function is not returning anything (I want to display them in an input). H ...

Implementing server authentication for page requests in a nodeJS and angularJS application

My application relies on passport.js for authentication. One of my main requirements is to prevent access to a specific page (e.g., '/restricted') for users who are not logged in. Currently, anyone can directly access the "localhost:3000/#/restr ...

Issues with loading cascading drop down list data from database using MVC, JSON, and C#

Hello everyone, I'm fairly new to MVC/Javascript and have been experimenting with different tutorials in order to create a cascading drop down list for selecting State and City on an MVC view. In my latest attempt, I followed this example. While the ...

Angular Modal Window is giving me a headache, can't seem to get it to work

I'm very new to Angular.js. I found a tutorial on creating modal windows in Angular.js by following this link: While I was able to make the code work independently, I've been struggling to get it working on my website after porting it over. Th ...

Eliminate classes from radios that are not selected

Here is a snippet of the code I am working with: <ul id="id_priori"> <li> <label for="id_priori_0"> <input id="id_priori_0" name="priori" type="radio">Hola </label> </li> </ul> ...

Ways to retrieve information from a different server utilizing AJAX

I am in need of fetching data from a file that is located at a different URL. Below is the code snippet that showcases the AJAX request being sent to the server. <script> alert('return sent'); $.ajax({ type: "POST", ...

Choose the child nodes upon selecting the root node

I am trying to implement a 2-level material-ui treeview where selecting the root node should automatically select all child nodes as well. Does anyone have suggestions on how to achieve this with material-ui treeview? For more information, please visit ma ...

The then method in AngularJS for handling $http requests

When attempting to use the $http method in my code, I encountered an issue where the code following the request was executed before the result was returned. As a result, the parameters of my response ended up being undefined. var reqgetcustomers = $http({ ...

Prevent postback from ImageButton OnCommand by utilizing JavaScript in asp.net 4.0 specifically for Internet Explorer

It seems like the Internet Explorer issue has resurfaced, and I'm struggling to resolve it: I have an ImageButton set up with OnCommand to delete a specific entry from my database. However, I've added a confirmation step for the user before dele ...

When attempting to chain middleware in next-connect, an issue arises with the error handler

I have the following pair of middleware functions: function validateEmail(req, res, next) { console.log('email validation'); if (req.body.email && req.body.email.match(EMAIL_REGEX)) { console.log('email OK!'); return ...

What is the method to enable Google Adsense to reach pages within a restricted login area that utilizes JSON authentication?

I am looking to place Google Adsense ads on my website, but I want them to only appear within a specific area that is accessible to users after they log in. Within the Google Adsense interface, I have explored the Account Settings -> Access and authori ...

Having trouble with nodeJS when running the command "npm install"?

Can anyone help me understand why I'm encountering issues when running "npm install"? Whenever I run npm install, I am bombarded with numerous errors. npm ERR! Windows_NT 10.0.10586 npm ERR! argv "C:\\Program Files\\nodejs&bsol ...

Having trouble accessing the POST RESPONSE json in ReactJS and NodeJS

I have set up my own API server that is connected to a MySQL database. Whenever I send a request to the server, everything seems fine. I can see the input from the browser and the output from the database in the console. However, I am unable to see any new ...

Leveraging jQuery and Ajax for extracting and transmitting parameters within href links

Here is my HTML link code: <div id="message"></div> <a href="cats.php?id=60&color=brown&name=kitty" id="petlink"> Click here </a> I want to use jQuery and Ajax to send these parameters when the link is clicked: id=60 colo ...

Ways to identify when a React child element is overflowing

tl;dr How can I create a component that hides overflow and toggles views with a button? For example, the user can initially see tabs 1, 2, and 3 while tabs 4, 5, and 6 are hidden. Clicking a button will hide tabs 1, 2, and 3, and show tabs 4, 5, and 6 with ...

In Angular, what is the best way to change the format of the timestamp '2019-02-22T12:11:00Z' to 'DD/MM/YYYY HH:MM:SS'?

I am currently working on integrating the Clockify API. I have been able to retrieve all time entries from the API, which include the start and end times of tasks in the format 2019-02-22T12:11:00Z. My goal is to convert the above date format into DD/MM/Y ...