Using AngularJS to dynamically change the background color of list elements based on data from a JSON file

I need assistance with setting a background color for each element in a list retrieved from a JSON file. I want to utilize the getNumber() function to generate a random number and assign a corresponding color to each list element. How can I dynamically set the background-color of each div by invoking the getNumber() function?

HTML code-

<html ng-app="ionicApp">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">

  <title>Radio Buttons</title>

  <link href="//code.ionicframework.com/1.0.0-beta.12/css/ionic.css" rel="stylesheet">
  <script src="//code.ionicframework.com/nightly/js/ionic.bundle.min.js"></script>
</head>

<body ng-controller="MainCtrl">

  <ion-header-bar class="bar-positive">
    <h1 class="title">Divs inside Div</h1>
  </ion-header-bar>

  <ion-content scroll="false">
    <ion-scroll class="list" direction="y" style="height:100%">
      <li class="item" ng-repeat="item in agendaDetails">
        <div class="row speakerListItems" ng-repeat="speakering in item.speakers track by $index">
          <div class="col-50">
            <p style="float:left">{{speakering.speaker}}</p>
          </div>
          <div class="col-50">
            <p style="float:right">Hello</p>
          </div>
        </div>
      </li>
    </ion-scroll>
  </ion-content>
</body> 
</html>

I would like to assign a dynamic background-color to each list item using the getNumber() function to determine the color based on a generated value. View the Codepen demo here - CODEPEN DEMO

Answer №1

Give ng-style a try with this example: view codepen sample

<ion-content scroll="false">
    <ion-scroll class="list" direction="y" style="height:100%">
      <li class="item" ng-repeat="item in agendaDetails">
        <div class="row speakerListItems" ng-repeat="speakering in item.speakers track by $index">
          <div class="col-50" ng-style="{'background-color': getNumber()}">
            <p style="float:left">{{speakering.speaker}}</p>
          </div>
          <div class="col-50" >
            <p style="float:right">Hello</p>
          </div>
        </div>
      </li>
    </ion-scroll>
  </ion-content>

Make sure to add the getNumber method to your $scope so it can be accessed from HTML

$scope.getNumber = function getNumber() {
    var minNumber = 1; 
    var maxNumber = 4; 
    var randomnumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber);
  //alert("randomnumber"+randomnumber);
  //alert($scope.colorDetails[randomnumber]);
  return($scope.colorDetails[randomnumber]);
}

Answer №2

After testing it out, I can confirm that everything is working smoothly. Take a look at the code below:

<html ng-app="ionicApp">

<head ng-app="ionicApp">
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">

    <title>Radio Buttons</title>

    <link href="//code.ionicframework.com/1.0.0-beta.12/css/ionic.css" rel="stylesheet">
    <style>
        .speakerListItems
        {
            border-bottom:1px solid white;
        }
    </style>
    <script src="//code.ionicframework.com/nightly/js/ionic.bundle.min.js"></script>
</head>

<body ng-controller="MainCtrl">

<ion-header-bar class="bar-positive">
    <h1 class="title">Divs inside Div</h1>
</ion-header-bar>

<ion-content scroll="false">
    <ion-scroll class="list" direction="y" style="height:100%">
        <li class="item" ng-repeat="item in agendaDetails">
            <div class="row speakerListItems" ng-repeat="speakering in item.speakers track by $index">
                <div class="col-50">
                    <p ng-style="{'background-color':getNumber()}">{{speakering.speaker}}</p>
                </div>
                <div class="col-50">
                    <p style="float:right">Hello</p>
                </div>
            </div>
        </li>
    </ion-scroll>
</ion-content>

<script>
            angular.module('ionicApp', ['ionic'])

                    .controller('MainCtrl', function ($scope) {
                        var agendaDetails = [
                            {
                                "startTime": "10:00",
                                "endTime": "12:00",
                                "topic": "INVESTOR RELATIONS & FINANCE OVERVIEW",
                                "speakers": [
                                    {
                                        "speaker": "Speaker1"
                                    }
                                ]
                            },
                            {
                                "startTime": "12:00",
                                "endTime": "2:00",
                                "topic": "ACQUISTION PROCESS",
                                "speakers": [
                                    {
                                        "speaker": "Speaker2"
                                    },
                                    {
                                        "speaker": "Speaker3"
                                    }
                                ]
                            },
                            {
                                "startTime": "2:00",
                                "endTime": "4:00",
                                "topic": "DIVERSITY OVERVIEW",
                                "speakers": [
                                    {
                                        "speaker": "Speaker4"
                                    },
                                    {
                                        "speaker": "Speaker5"
                                    },
                                    {
                                        "speaker": "Speaker6"
                                    },
                                ]
                            },
                            {
                                "startTime": "10:00",
                                "endTime": "12:00",
                                "topic": "INVESTOR RELATIONS & FINANCE OVERVIEW",
                                "speakers": [
                                    {
                                        "speaker": "Speaker7"
                                    },
                                    {
                                        "speaker": "Speaker8"
                                    },
                                    {
                                        "speaker": "Speaker9"
                                    },
                                    {
                                        "speaker": "Speaker10"
                                    },
                                ]
                            }
                        ];
                        $scope.agendaDetails = agendaDetails;
                         var colorDetails = {
                            "1": "red",
                            "2": "blue",
                            "3": "black",
                            "4": "white",
                            "5": "green"
                        }
                        $scope.colorDetails = colorDetails;

                        $scope.getNumber = function (){
                            var minNumber = 1;
                            var maxNumber = 4;
                            var randomnumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber);                                
                            return($scope.colorDetails[randomnumber]);
                        };
                    });
</script>

The solution lies in using ng-style. If we attempt to use style="background-color:red or getNumber() and encounter issues, make sure not to include quotes when calling a function.

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

The implementation of gulp-less encounters issues when the !important rule is applied

When the !important declaration is used on a specific less variable, it causes the build to fail. The use of !important is common in our codebase, so it's puzzling why this particular instance is causing an issue. Setup: customer1.less @import "bas ...

Backdrop in Bootstrap Modal Does Not Fully Cover Buttons and Input Fields

Currently, I am working with mysql and php on a user.php page that caters to user interactions. The main content in the center <div> is dynamically updated through php whenever a link on the same page is clicked. To elaborate, when a user clicks on a ...

Refreshing the form fields and storing the information using AngularJS

I have successfully implemented a basic form using AngularJS. The issue I am facing is that even after the user enters their details and submits the form, the values remain in the input fields. My goal is to store the details of multiple fields in the con ...

The touch event doesn't seem to be functioning properly on the div element, but it works perfectly on the window element

I have a dilemma that's been puzzling me lately. I'm trying to append a touchevent to a div, but my current method doesn't seem to be working. Here's what I've tried: $("#superContainer").bind('touchstart', function(even ...

How to conceal the day picker in jQuery UI datepicker

I am facing a problem that has been addressed before. As someone with only basic knowledge of CSS, I am a bit confused here. I have two datepickers in my code. <style> .ui-datepicker-calendar { display: none; } </style> Unfortunately, ...

Utilizing various image galleries within Twitter Bootstrap Tabs

I have incorporated three different image galleries using the SlidesJS plugin and placed them within tabs of Twitter Bootstrap. To see a demo, click here. While the first gallery is displaying correctly within its tab, the images for the second and third ...

$http.get() consistently encounters issues on Windows Phone (versions 7 and 8)

My application (built with AngularJS and Cordova/PhoneGap) successfully pulls JSON content from a remote server on Android and iOS devices. However, I am experiencing consistent failures when attempting the same request on Windows Phone. Here is an excerpt ...

Trouble with the 'first-child' selector in jQuery

<html> <head> <style type="text/css"> .hori { color:red; } </style> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"> </script> <script type="text/javascript"> $(document). ...

Using filter to convert a string into an array and then utilizing it in ng-repeat functionality

I have a string in the format of "1200:2,1300:3,1400:2" that I need to display like this: <p>1200</p><p>2</p> <p>1300</p><p>3</p> <p>1400</p><p>2</p> I attempted to use a filter, ...

Why does Jade convert && to & when used within an AngularJS in a Jade template?

Utilizing AngularJS within Jade templates alongside ExpressJS. This specific code snippet is part of my form validation in the Jade template. div(ng-show="form.username.$dirty && !signup_form.name.$focused") After rendering the Jade template and ...

Customizing Forms with Bootstrap Styling in HTML

Is there a way to rearrange this list so that the buttons appear above the textboxes, like in the desired formatting example The code is as follows: <form id="Data" runat="server" class="p-3 mb-2 bg-primary text-dark"> <div class="form-gr ...

Tips for locating the bug line or file in Angular 2

I am currently following the Angular hero tutorial, and I have reached the Routing step. However, I encountered an issue with my script not working properly. The default template only displays "Loading..." text, indicating that there is an error in one of ...

What is the best way to show emojis in AngularJS?

Recently starting to work with angularjs, I've incorporated "emoji-min.js" and "emoji-min.css" into my project as an attempt to display emojis within a text field. Despite my efforts, the emojis are not displaying as intended. Here is a snippet of my ...

Steps for obtaining character index upon clicking in HTML:

Is it feasible to determine the character index onClick in relation to the HTML body? I attempted to find a solution, but my efforts were in vain. Unfortunately, I am unable to utilize Jquery because I am working with Angular JS / Ionic. ...

Error injecting angular.bootstrap in Angular 1.6.5 version

I have a MeanJS.org skeleton app that I've transformed into hapi-js from express, switched to postgres from mongo, and incorporated OAUTH for authentication (mainly because I liked the server/client module folder structure - haha). Everything seems t ...

Unable to reduce the height of the li element

Even though I've attempted to adjust the height of the lis in this section using CSS, I can't seem to shorten them as desired: I've experimented with setting a line-height, adjusting the height, ensuring that paddings and margins are set to ...

Leveraging Angular UI-Router in conjunction with Phonegap

My current project is developed using Angular and I'm deploying it to the Phonegap Build service for iOS and Android distributions. Initially, I used Angular's routing service but had to switch to Angular UI-Router due to nesting multiple views r ...

Having trouble with getting text centered in a div using 'vertical-align' property?

Can't seem to figure out why my text is not vertically aligning in the div. Here's the code I have: <div class="container"> <p>Hello world</p> </div> Accompanied by the following CSS: .container{ width: 100%; ...

Eliminating the appearance of horizontal scroll bar by employing transform scale to zoom out

When you run the code provided in the link below and scale down the HTML to 50% while increasing the width to fit the window, a scrollbar becomes visible. This only occurs in Chrome and not in Firefox. Click here The content of the DOM can be modified and ...

Expanding rows in Angular UI-Grid: Enhancing user experience with hover functionality

Struggling to add a hover effect to the rows in an Angular UI grid. The goal is for the entire row to change background color when hovered over, but with an expandable grid that includes a row header, applying CSS rules only affects either the row header o ...