Alter the background color upon clicking using ng-click

I am a beginner in using Angular, and I am currently working on a CodePen project. My goal is to change the background color of another div based on the color of the button clicked by the user at the bottom navigation. However, I am uncertain about the best approach to achieve this. Below is the code snippet that I have been working with.

Link to the CodePen editor: http://codepen.io/modDesigns/pen/YyKwGj

HTML:

<div class="wrapper" ng-app="mobile">
<div class="phone">
    <div class="page" ng-controller="Screen">
        <div class="top_background" ng-style="{'background-color': changeScreen()}">
            <i class="fa fa-signal sigs"></i>
            <i class="fa fa-wifi sigs"></i>
            <i class="fa fa-battery-full bats"></i>
            <span class="times">11:44am</span>

            <div class="home">
                <h5 class="text-center"><i class="fa fa-user"></i>   Account</h5>
            </div>
            <div class="navigation">
                <div class="col-sm-3 homes" ng-style="{'background-color': '#C0392B'}" ng-click="changeScreen('#C0392B')">
                    <h4><i class="fa fa-home"></i></h4>
                </div>
                <div class="col-sm-3 shop" ng-click="" ng-style="{'background-color': '#E74C3C'}">
                    <h4><i class="fa fa-shopping-cart"></i></h4>
                </div>
                <div class="col-sm-3 feeds" ng-click="" ng-style="{'background-color': '#E67E22'}">
                    <h4><i class="fa fa-comment"></i></h4>
                </div>
                <div class="col-sm-3 settings" ng-click="" ng-style="{'background-color': '#F39C12'}">
                    <h4><i class="fa fa-cog"></i></h4>
                </div>
            </div>
        </div>
    </div>
</div>

Javascript:

var app = angular.module('mobile', []);
app.controller('Screen', function($scope) {
$scope.changeScreen = function(myClass) {
    $scope.theClass = myClass;
    return $scope.theClass;
};

});

Answer №1

Instead of creating a new function for additional functionality, you can achieve what you need by utilizing ngClick to assign a variable and then use that variable as the background color directly in your HTML.

http://codepen.io/anon/pen/JYPJBR

<div class="wrapper" ng-app="mobile">
  <div class="phone">
    <div class="page" ng-controller="Screen">
      <div class="top_background" ng-style="{'background-color': screenColor}">
        <i class="fa fa-signal sigs"></i>
        <i class="fa fa-wifi sigs"></i>
        <i class="fa fa-battery-full bats"></i>
        <span class="times">11:44am</span>

        <div class="home">
          <h5 class="text-center"><i class="fa fa-user"></i>   Account</h5>
        </div>
        <div class="navigation">
          <div class="col-sm-3 homes" ng-style="{'background-color': '#C0392B'}" ng-click="screenColor='#C0392B'">
            <h4><i class="fa fa-home"></i></h4>
          </div>
          <div class="col-sm-3 shop" ng-click="screenColor='#E74C3C'" ng-style="{'background-color': '#E74C3C'}">
            <h4><i class="fa fa-shopping-cart"></i></h4>
          </div>
          <div class="col-sm-3 feeds" ng-click="screenColor='#E67E22'" ng-style="{'background-color': '#E67E22'}">
            <h4><i class="fa fa-comment"></i></h4>
          </div>
          <div class="col-sm-3 settings" ng-click="screenColor='#F39C12'" ng-style="{'background-color': '#F39C12'}">
            <h4><i class="fa fa-cog"></i></h4>
          </div>
        </div>
      </div>
    </div>
</div>

If you're facing issues with your current code, it's because changeScreen() is not configured to work as both a getter and a setter simultaneously. You have two options to address this:

<div class="top_background" ng-style="{'background-color': theClass}">

Or adjust the function to handle cases where theClass is undefined when invoked without arguments:

$scope.changeScreen = function(myClass) {
  if(angular.isDefined(myClass)){
    $scope.theClass = myClass;
  }
  console.log('the class', $scope.theClass);
  return $scope.theClass;
};

Answer №2

Check out this codepen for what you requested:

http://codepen.io/anon/pen/rOBwZV

Only the HTML has been modified:

<div class="wrapper" ng-app="mobile" ng-init="bgCol='#F39C12'">
<div class="phone">
<div class="page" ng-controller="Screen">
  <div class="top_background" style="background-color: {{bgCol}}">
    <i class="fa fa-signal sigs"></i>
    <i class="fa fa-wifi sigs"></i>
    <i class="fa fa-battery-full bats"></i>
    <span class="times">11:44am</span>

    <div class="home">
      <h5 class="text-center"><i class="fa fa-user"></i>   Account</h5>
    </div>
    <div class="navigation">
      <div class="col-sm-3 homes" ng-style="{'background-color': '#C0392B'}" ng-click="bgCol='#C0392B'">
        <h4><i class="fa fa-home"></i></h4>
      </div>
      <div class="col-sm-3 shop" ng-click="bgCol='#E74C3C'" ng-style="{'background-color': '#E74C3C'}">
        <h4><i class="fa fa-shopping-cart"></i></h4>
      </div>
      <div class="col-sm-3 feeds" ng-click="bgCol='#E67E22'" ng-style="{'background-color': '#E67E22'}">
        <h4><i class="fa fa-comment"></i></h4>
      </div>
      <div class="col-sm-3 settings" ng-click="bgCol='#F39C12'" ng-style="{'background-color': '#F39C12'}">
        <h4><i class="fa fa-cog"></i></h4>
      </div>
    </div>
  </div>
</div>
</div>

Answer №3

Your code seems to have a small issue that needs attention. You can refer to this example to understand how it functions.

The main problem lies in how you are calling the method in your HTML:

    <div class="top_background" ng-style="{'background-color': changeScreen()}">

Note that no parameter is being passed to the method, whereas in AngularJS, the method is expecting a class name. It would be more efficient to encapsulate the entire style within an object, as shown in the example provided. This way, any additional style properties can easily be included without the need for another function call within ng-style.

I hope this explanation helps clarify things for 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

Sending PUT and DELETE requests in a Laravel application hosted on a shared server

I have developed a unique Laravel CMS application that is functioning perfectly on my local environment. Now, I am attempting to deploy it on a shared hosting server. To achieve this, I have organized all Laravel app files and folders (excluding public) i ...

D3 diagram within a Bootstrap Modal-Dialog

Issue #1: I am encountering an issue with a dynamic modal-dialog containing a diagram. The code appears to be straightforward: https://jsfiddle.net/c2abnhja/1/ Upon inspection, it is evident that the diagram does not appear within the designated div con ...

I'm encountering errors from JQuery right from the start of the code

Hey there, I encountered a problem with my script: $(document).ready(function(){ alert("works"); }) I tried using a regular document.ready check but it keeps throwing 7 errors at me. Check out the screenshot of the errors here Any help or advice wo ...

How to change the date value in an HTML input field of type date using JavaScript

Struggling with manipulating an HTML date input type using javascript? You're not alone. The common approach to manipulating the date is like this: var c = new Date(); c.setDate(c.getDate() + 1); You can get the date from the input element: c = do ...

Sorry, I cannot fulfill this request as it is already a unique error message

I've been working through a Node.js and MongoDB tutorial using JavaScript (). However, I encountered an issue when running Node and MongoDB from the terminal and accessing http://localhost:3000/items. It seems to be related to this specific code bloc ...

What is the best way to transform an array of objects into a single string in JavaScript?

After receiving the input from req.body, it looks like this: [ { "Name": "Test_1", "Level 1": "Story_1", "Level 2": "Story_1.1" }, { "Name": & ...

How can we utilize dynatree.js lazy loading to eliminate null child nodes (i.e., every final node in a branch is null)?

I just started using dynatree and so far it's been great with lazy loading. However, I'm facing an issue where the last child is displaying as null for every branch. $("#tree").dynatree({ title: "Lazy loading sample", fx: { height: "togg ...

Leveraging Deferred in conjunction with AJAX

I am facing an issue with a series of JavaScript functions that make database calls using AJAX. I need these functions to finish executing and update variables before moving on to the final function. I have attempted to use jQuery $.when but it is not work ...

Cannot complete request: CORS issue encountered in AngularJS

I recently started using AngularJS and I'm trying to integrate the Paytm wallet into my web application. However, when I attempt to send a request to the Paytm server from my AngularJS function, I encounter the following error: Cross-Origin Request ...

What are some strategies for improving search efficiency in arrays containing over 50,000 elements?

I am working with a large array of strings containing about 50,000 elements. export const companies = [ "000014", "000016", "000017", "000019", "000020", "000021", "000023" ...

Troubleshooting problems with email templates using Handlebars JS within Nest JS

I am encountering an issue while using Handlebars JS in my Nest JS project to send emails. Although the email is sending properly, the content of the email body is not rendering correctly, resulting in responsiveness and styling problems. In my template: ...

What is the formula for determining the size of an image using JavaScript, jQuery, or Java?

I'm looking to determine the dimensions of an image. I have both the image src and base64 data available. My goal is to display the current size of the image. I am working with Java and JavaScript. Is there a way for me to calculate the image size usi ...

Exploring function overloading in Typescript using custom types

I encountered an issue here that I believe has 2 possible solutions. Let's start with my initial implementation using function overloading: type PostgresConnectionOptions = { dialect: "postgres"; config: pg.PoolConfig; }; type MysqlConne ...

What is the best way to recycle or invoke a function in Angular from a different file?

I have a function in file1.ts that acts as a converter. I am looking to reuse this function in file2.ts. Any suggestions or ideas? Thank you! #Code formatBytes(bytes, decimals = 2) : string | number { console.log("lol") if (bytes === 0) { r ...

Alter the hue of the div

Having trouble with this code snippet: function red(opt) { var sqr; sqr="r"+parseInt(opt); hilight_css = {"background-color":"#f00"}; $(#sqr).css(hilight_css); } I am calling the function like so: red(questions); The variable question ...

Tips for creating a clickable title that directs to a URL

I am currently using the "Import All" WordPress plugin to bring in an Excel file containing numerous hyperlinks that point to specific Custom Post Types and a designated field. These hyperlinks are separated by commas from the corresponding title. For exam ...

In AngularJS, the process of delivering JavaScript files alongside HTML is known as routing

As I develop an AngularJS application, I am working on a service that generates a unique link for users to share, such as localhost:8080/sync/03afdbd66e7929b1. This link is intended to lead users to a form. However, upon configuring the route to handle thi ...

Update the content within a div based on the selected option from a dropdown menu or

Is there a way to change the displayed text based on user input or selected option? By default, the text shown is "Aa Bb Cc Dd Ee...", but it can be changed by selecting different options. If text is typed into the input field, the displayed text will up ...

Is there a way to delete added information using a trigger that has been inserted through ajax?

I created a function in jQuery and Ajax to add information from a separate PHP file to another file. Let's name the destination file "Homepage" and the file with the data "Template". Here is the function I used: var box = $('#infoPageContainer& ...

"The Jquery new Date function is returning inaccurate data when trying to pass it in the format yyyy dd

While utilizing remote desktop, I have come across the following code snippet in my JavaScript file: var birthday = new Date(2017, 1, 1); console.log(birthday); The output generated is as follows :- Wed Feb 01 2017 00:00:00 GMT+0000 (Coordinated Univ ...