Modify the div's background color specifically with AngularJS

After creating a list using divs, my goal is to modify only the background color of the selected div when a user makes a choice from the list.

I have accomplished this by defining two distinct CSS classes with the main difference being the background color, and then applying the appropriate style when a user selects a div.

Is there a way to alter only the background color without impacting the existing style using angularJS?

Answer №1

I am just diving into the world of AngularJS, so this assignment is a great learning opportunity for me. I understand that my approach may not be perfect or exactly what you are looking for. Please review and let me know if there is room for improvement.

Currently, I have tackled this task by creating two distinct CSS classes with the only variance being the background color.

You could organize the background colors into separate classes and simply toggle between them while keeping everything else constant.

HTML

<div ng-app ng-controller="testCtrl" >
  <div ng-repeat="item in items">
    <div ng-class="item.class" ng-click="select(item)">{{item.text}}</div>
  </div>
</div>

JS

function testCtrl($scope) {
  $scope.items = [
    { text:'List item 1', class:'default normal' },
    { text:'List Item 2', class:'default normal' },
    { text:'List Item 3', class:'default normal' }
  ];

  $scope.select = function(item) {
    angular.forEach($scope.items, function (value, key) {
        if(value == item) {
        value.class = 'default select' // selected
      }
      else {
        value.class = 'default normal' // restored
      }
    });
  };
}

CSS

.default { font-size: 25px; padding: 10px; margin-bottom: 5px; }
.normal { background: yellow; }
.select { background: cyan; }

Check out the JSFiddle demonstration here.

Answer №2

Feel free to use this solution for adding an active class to a clicked item:

app.controller('MainCtrl', function($scope) {
    $scope.items = [
        'Page One',
        'Page Two',
        'Page Three'
    ];

    $scope.selected = 0;
    $scope.active = function(index) {
        $scope.selected = index;
    }
});



<li ng-repeat="item in items">
            <a ng-class="{ active : $index == selected }" ng-click="active($index)">{{ item }}</a>
        </li>

Check out the demo on fiddle

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

Origin Access-Control-Allow Not Recognized

Currently, I am developing a node.js app and have encountered a strange issue: This particular Angularjs snippet... // delete hosts $scope.delete = function(row) { var rowData = { hostname: row.hostname, ipaddr: row.ipAddress, ...

Utilizing custom filters to navigate through nested ng-repeats

My goal is to achieve a specific behavior by using custom filters. I am working on creating a unified search bar that will display entire group names with all failing students, as well as group names with only the matching students. If you want to see the ...

`Center Google My Map Location - Embedded in the Middle of the Page`

Recently, I transitioned to using an embedded My Map for a business with 2 locations. However, I encountered some challenges in customizing the map's height, width, and centering on the page. Is there a way to resolve this issue? New HTML code which ...

What is the best way to showcase additional fields from a custom post type along with the featured thumbnail feature?

'I designed a custom post plugin in Wordpress that successfully displays the title and main content, but I am facing issues with displaying other fields such as company details. Despite mentioning a featured thumbnail option in my plugin, I am not ab ...

Modify all the content within the DIV using Regex, while keeping the HTML tags intact

I am attempting to replace all the text inside a DIV, including within its children, without modifying any HTML tags. Specifically, I want to switch all instances of 'Hello' to 'Hi'. Thank you for your help. var changes = $('div ...

How to position multiple CSS background images effectively?

Greetings all! I'm seeking advice on how to add a background image to the right of the description and left of the first post column. Any tips on proper placement? Appreciate any help :) ...

What steps can be taken to prevent a "Flash of Unstyled Content" when using fixed-width cells in CSS Tables?

My website's design is heavily influenced by CSS tables. This decision was made to ensure consistent cell heights regardless of the content, making alignment easier. Overall, this method has been quite effective. However, there is an issue where the ...

Placing the video at the center of the background image

                    Can someone assist me with a design issue I'm facing? I have two divs within a section. The left div contains a heading and a button, while the right div contains a video. However, when I try to add a background image to ...

Angular's ngRoute is causing a redirect to a malformed URL

Currently, I am in the process of developing a single-page application using AngularJS along with NodeJS and Express to serve as both the API and web server. While testing locally, everything was working perfectly fine. However, after cloning the repositor ...

Some characters are not compatible with the CSS writing-mode feature

There seems to be an issue with the CSS writing mode not applying correctly to the symbol '№'. Here is an example: <html> <head></head> <body> <p style="writing-mode: vertical-lr;"> Номер № ...

Exploring the power of Google Maps Radius in conjunction with AngularJS

I am currently developing an AngularJS app that utilizes a user's location from their mobile device to create a dynamic radius that expands over time. You can view the progress of the app so far by visiting this link: . The app is functional, but I a ...

Issue with the alignment of a sidebar on a website's html page

Last week, I embarked on the journey to learn HTML and CSS. To put my skills to the test, I decided to recreate an old web page using what I have learned so far. The specific page I am trying to emulate can be found here: However, I am currently facing so ...

The hyperlink element is failing to load in a particular frame

I've been attempting to load the URL of an anchor tag in a specific frame. I've tried various methods through online searches, but have not found a satisfactory solution. Can someone please assist me with how to load the href URL in a particular ...

Tips for recognizing components within the #document are as follows:

I am currently utilizing xpath to extract data from a dynamic table in an HTML document. The specific information I am looking for is contained within a tag identified as #document. However, I am encountering difficulties including this unique element in ...

Illustrating a fresh DOM element with intro.js

I am currently utilizing intro.js to create a virtual 'tour' for my website. As I aim to provide a highly interactive experience for users, I have enabled the ability for them to engage with highlighted DOM elements at different points in the tou ...

Achieving data synchronization and sequencing with AngularJS promises at a 1:1 ratio

Concern I am facing challenges with AngularJS promise synchronization and sequencing as my app expands across multiple controllers and services. In this scenario, I have an articles controller named ArticleController along with a related service named Art ...

A guide to accessing files and displaying their content by utilizing button clicks in PHP

Is it possible to navigate through the files in a folder by using buttons like Next and Previous, and then display the file contents within a table cell? Below is my attempted output, which unfortunately isn't functioning as expected: View Sample Ou ...

Navigate the user to various pages in a Node.js application based on login status

Looking for guidance on a login system within my application? I need to redirect users based on their roles. Below is the code for the login controller, along with node.js snippets and the login HTML page. Any help would be appreciated. Login.html - < ...

Could jQuery and CSS be utilized for image enlargement?

Is it possible for jQuery (or CSS!) to detect an area around the mouse when hovering over an image, capture the image underneath, and then zoom in on that area? This concept differs from typical jQuery zoom effects where there are two separate images - sm ...

I'm utilizing bootstrap to design a slider, but the length of the second div inside it is longer than the slider div

To ensure that the second div appears above the slide div, I applied position:absolute to the second div. Since the first div is a slider, nesting the second div inside it was not feasible. How can this issue be resolved? <div class="carousel slide"> ...