Dealing with conditional CSS problems in Angular - a solution needed?

Is there a way to maintain the CSS class for the first property ID even when clicking on a second property ID? Currently, the CSS class is removed from the first property ID when a second one is clicked. How can I make sure the CSS class remains for the first property ID until it is specifically removed?

Below is the code snippet:

<div class="hmpal-prprt-post-wdgt hmpal-prprt-wishlist" 
    ng-click="WishlistAdd($index,project.propertyId)" 
     ng-class="getClass($index)" 
     ng-repeat="prop in homepalGroupProp.properties">
    <a href=""> 
        <span class="prprt-icon">
            <i class="fa fa-heart" aria-hidden="true"></i>
        </span> 
        <span>Wishlist</span> 
    </a>
</div>

Here is my controller code:

var selectedProductId = null;
a.selectedIndex = -1;
a.WishlistAdd = function ($index, propertyId) {
    if ($index === a.selectedIndex) {
        a.selectedIndex = -1;
    } else {
        a.selectedIndex = $index;
    }
    selectedProductId = (selectedProductId === propertyId ? null : propertyId);
    var data = {
        wishlistFlag: (selectedProductId !== null),
        propertyId: propertyId
    };

    e.createWishLists(data).then(function (result) {
        console.log(JSON.stringify(result));
        a.wishlistFlag = result.config.data.wishlistFlag;
        alert(a.wishlistFlag);

    }, function (error) {
        alert("error");

    });

}

Function for adding the class:

 a.getClass = function(ind){
        if( ind === a.selectedIndex ){
            return "selected";
        } else{
            return "";
        }
    }

Answer №1

Make some modifications to the ng-click and ng-class attributes in the following way:

ng-click = "selectedIdx = $ix" 
ng-class = "selectedIdx == $ix ? 'customClass':''" 

No additional Controller Code is necessary for this.

Cascading Style Sheets (CSS)

.customClass {
  background-color: navy;    
}

Answer №2

Here is a code snippet that demonstrates the usage of ng-class as per your requirements. Feel free to use it for your project.

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
        <style>
            .SelectionContainer {
                width: 100px;
                height: 100px;
                background-color: #efefef;
            }
            
            .ErrorSelect {
                background-color: red;
            }
        </style>
    </head>

<body>

    <div ng-app="myApp" ng-controller="myCtrl">

        <select ng-options="Option.Code for Option in OptionList track by Option.Id" ng-model="SelectedOptionValue"></select>
        
        <div class="SelectionContainer" ng-class="IsErrorSelected()"></div>
    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope) {
            $scope.SelectedOptionValue = {Id: "", Code: ""};
            $scope.OptionList = [{Id: 1, Code: "Option1"},
                                 {Id: 2, Code: "Option2"},
                                 {Id: 3, Code: "Never Select"},
                                 {Id: 4, Code: "Option4"}];
            
            $scope.IsErrorSelected = function(){
                var returnVal = ($scope.SelectedOptionValue.Id == 3)? "ErrorSelect": "";
                return returnVal;
            }
        });
    </script>

</body>

</html>

Answer №3

For checking the selected index in ng-class, you can refer to the code snippet provided below:

<div class="hmpal-prprt-post-wdgt hmpal-prprt-wishlist" 
        ng-click="clickedIndex = $index ;WishlistAdd($index,project.propertyId)" 
         ng-class="clickedIndex == $index ? customCss : ''" 
         ng-repeat="prop in homepalGroupProp.properties">
        <a href=""> 
            <span class="prprt-icon">
                <i class="fa fa-heart" aria-hidden="true"></i>
            </span> 
            <span>Wishlist</span> 
        </a>
</div>

Here is an example of custom CSS styling:

.customCss {
// css code
}

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

Having trouble updating a MongoDB array through a RESTful API PUT request

I'm brand new to the MEAN stack and recently completed a tutorial. I've been working on enhancing a simple application that utilizes a RESTful API to update a MongoDB. Currently, I'm using a PUT statement to modify specific parts of my colle ...

Adding HTML content to routes in ExpressOrEnhancing routes

Recently, I've been working with a basic index.html file. My goal is to have the routes file append an HTML button when requested by the browser without actually modifying the original file. This may seem like a peculiar idea, but my intention is to c ...

Is there a way to determine if a webpage is being accessed from a website or from a local file system?

While this question has been raised in the past, none of the answers provided seem to be accurate. Unfortunately, I am unable to comment on the original question or answers. Thus, following suggestions given to me, I have decided to create a new question. ...

Waiting on the Google API, but unfortunately the sleep function is not cooperating

Incorporating the Google Maps API into my svelte project has been a task. I've turned to the js-api-loader npm package for this purpose. Below is the code snippet I'm using to load the Google API: loader.js import { Loader } from '@googlem ...

Initial loading size of Google chart

After creating a Google chart, I noticed that on the initial load, the chart appears tiny. Although it becomes responsive when adjusting the screen size, I would prefer it to be responsive from the start. Please note that there is a dropdown menu for sele ...

Selenium struggles to display any content within the innerHTML/innerText of a particular element

When using Selenium, why does the following function output an empty string when trying to retrieve the 'innerHTML' attribute of an element? This behavior remains the same even if attempting to fetch the 'innerText' attribute instead. ...

Spinning a 3D surface about an axis using JavaScript

I'm in need of guidance on what to implement, unsure whether to use vanilla JavaScript or a library. My goal is for users to view a 3D model building in their browser. The modeling is done in a specific tool and then exported as a sequence of images ...

Personalized tooltips for numerous data sets in Highcharts

I am currently in the process of constructing a highchart that is capable of accommodating up to five different types of data series. I have arranged similar series together, resulting in three distinct y-axes for the various series. However, I have encou ...

Encounter an issue with the Kendo editor React wrapper showcasing an error

Looking to incorporate an editor using Kendo UI, but encountering an error TypeError: list is undefined in node_modules/@progress/kendo-ui/js/editor/plugins/inlineformat.js:422 The library was installed through: npm install --save @progress/kendo-editor- ...

Tips for maintaining the button color when clicking and refreshing the page

By default, the color of my like button is gray. When a user clicks the like button, it will trigger the togglepost "like" function and the color will change to red. I am using AJAX to insert the data when the like button is clicked. If the user clicks the ...

Angular has the capability to rewrite URLs in CSS, providing a unique way

An issue arises in Angular when using a base set and html5mode with SVGs. This causes things like filter: url(#url) to be rewritten as filter: url(/base/#url). https://github.com/angular/angular.js/issues/8934 Disabling html5 mode and removing the base d ...

Utilizing Dynamic URLs in Kendo for Data Binding or Attributes on List Elements

I am facing an issue with routing two menu items conditionally using Kendo Jquery/MVVM. Originally, I had set the value in a data-href tag and it was displaying the URL correctly. However, I now need to dynamically load a URL based on certain conditions. T ...

What's going on with this unresponsive button in the login system?

I am facing an issue where my code does not respond when I click the login button with the correct login details. Following some suggestions from the comments, I have modified the code to include an onClickHandler function. However, I am unsure which arg ...

Retrieving the information verified in the database

public function actionEditmul($id) { $sql1="SELECT * FROM category_product INNER JOIN category ON category_product.cat_id=category.cat_id WHERE category_product.product_id=$id"; $editcat=Yii::$app->db->createCommand($sql1)->quer ...

How to loop through an array in JavaScript using a for loop?

Currently, I am engaged in a CSRF lab exercise with the challenge of iterating through over 20 tokens. <script> var token = ["f23e7b8c79d33d39ea67f0062b2cdb23", "90b157ac841c5aa7854285ea225c18e3", "9a189a1ef6a01aae6a298a0594831b66"]; var arr ...

What is the best way to position an image in the middle of a Bootstrap 5 Carousel?

I utilized the Bootstrap documentation and everything is functioning properly, but I am facing an issue with aligning the logo in the center of the carousel, especially when the image transitions. I attempted using a relative parent element, but it seems ...

Using .done(), .then(), and .when() in jQuery for sequencing ajax requests in a specific order

After diving into the world of Promises in jquery and trying to avoid "callback hell" when dealing with multiple ajax requests, I still find myself without a clear answer on which method to use - whether it's .done(), .then(), or .when() - for chainin ...

To use the ModuleWithProviders<T> in the angular-autofocus-fix package, you must provide 1 type argument

Upon successful installation of angular-autofocus-fix I have imported the AutofocusModule However, upon running the Angular project, I encountered the following error: ERROR in node_modules/angular-autofocus-fix/index.d.ts:4:23 - error TS2314: Generic ty ...

Anticipating the resolution of the $rootScope value in Angular before the page is fully loaded

I've encountered an issue while using ngView with a static navigation bar that persists throughout the application: <div ng-include="'views/nav.html'" ng-controller="NavCtrl"></div> <div class="container-fluid" ng-view=""> ...

Check to see if modifying the HTML using jQuery results in any errors

Although it may sound straightforward, let me clarify. I am utilizing ajax calls to update the content of the body and I aim to trigger an alert if the updating process fails on the client side, specifically after receiving a response from ajax in case of ...