Using ng-class with a function invocation that creates a random string

I am currently working on my Angular app using the Materialize Library. I'm facing an issue where I want to assign a random class name to each tag so that the background color is different for each one.

<ul class="inline-list" ng-repeat="feature in features">
 <li class="chip" ng-class="getColor()">{{feature}}</li>
</ul>

Here's my controller:

function ProjectsController($scope) {
    $scope.features = ['React', 'Redux', 'Firebase'];
    const colorClass = ['pink lighten-3', 'indigo lighten-2', 'lime accent-1',
     'amber accent-2','grey darken-2', 'deep-orange darken-1', 'green accent-2', 
     'teal', 'purple', 'red darken-1'];
    $scope.getColor = () => {
      return colorClass[Math.floor(Math.random()*10)]
    }
}

However, I'm encountering an error in the browser:

angular.js:10633 Error: [$rootScope:infdig]

I would appreciate any hints or clues on how to solve this problem.

Answer №1

It appears that you may be stuck in an infinite loop of $scope.digest().

Please refer to the documentation regarding the [$rootScope:infdig] error:

I recommend restructuring your controller as follows:

function ProjectsController($scope) {

   const colorClass = ['pink lighten-3', 'indigo lighten-2', 'lime accent-1',  'amber accent-2','grey darken-2', 'deep-orange darken-1', 'green accent-2', 
 'teal', 'purple', 'red darken-1'];


  function getColor() {
     return colorClass[
             Math.floor(Math.random() * 10 )
          ]
  }

  $scope.features = [
         { technology: 'React', color: getColor() },
         { technology: 'Redux', color: getColor() },
         { technology: 'Firebase', color: getColor() },
  ];
}

Additionally, remember to update your HTML structure:

<ul class="inline-list" ng-repeat="feature in features">
    <li class="chip" ng-class="feature.color">{{feature.technology}}</li>
</ul>

Hoping this information proves useful.

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

Using setState in an external function: A step-by-step guide

import Request from 'superagent'; const fetchApi = () => { let apiUrl = '/* URL */'; return Request.get(apiUrl).then((response) => { this.setState({ data: response.body }); }); } export d ...

Switching ng-Idle countdown time from seconds to minutes is possible by adjusting the configuration settings

I have implemented ng-idle in my application, where the warning popup appears after 10 seconds with the message: "Your session will be close in 10 seconds" However, I need to change this to minutes. The session should be closed in 5 minutes instead. How ...

What is the reason behind the default disabling of bootstrap multiselect options?

Just diving into the world of bootstrap and I'm puzzled as to why my simple multiselect options aren't responding when clicked. UPDATE The first multiselect option on the test-site linked below is the one giving me trouble. I've tried it o ...

Is there a way to view an image before and after uploading it?

I am encountering an issue while attempting to display a preview of an image in a form. The HTML code involved is as follows: <form action="" method="post" enctype="multipart/form-data" name="personal_image" id="newHotnessForm"> <p><lab ...

Can you always rely on promises being fulfilled?

Consider a scenario where we have a function named logData to handle HTTP requests and another function called logIntoDatabase. async logIntoDatabase(message) { ... } async logData(request, response) { await logIntoDatabase("something happened"); ...

Tips on obtaining outcome by invoking a route outside of app.js

Within my file containing the request methods, the structure appears as follows: article.js router .route("/") .all((req, res) => { console.log("this should happen for any call to the article route"); }) .get((req, res) = ...

How to delete a div element in Material UI's Date Picker

In my project, I am utilizing Material UI's simple Date Picker module. However, I am looking to solely display the calendar section without the month and year indicators along with the navigation arrows. Is it possible to remove these specific element ...

What is the maximum length for the string that can be passed to jQuery's .append() method?

In Angular, I developed a simple program that leverages router functionality to showcase two pages within a single-page application. The setup includes a page with two navigational buttons and a wrapper div (ng-view) that dynamically displays the content o ...

What is the best method to substitute a comma and period with just a period in a textarea

Creating a text area with auto-replacing characters like straight quotes, double dashes to em dash, and double spaces to single space was simple. However, I'm facing difficulty in adding a script for replacing certain characters: word . as word. wor ...

Utilizing React Router: Combining MemoryRouter and Router for Dynamic Routing (leveraging memory for certain links while updating the URL for others)

While utilizing react-router-dom, I came across the helpful <MemoryRouter>. However, I am in need of having several routes that can read and write to/from the browser's URL. What is the best approach for implementing this functionality? Thank y ...

Tips for dynamically updating the path in angular as you scroll

https://i.stack.imgur.com/KlmnQ.jpg Currently utilizing Angular 17, my goal is to create a page with multiple components accessible through unique paths. Clicking on the navigation menu should automatically scroll to the desired component and update the p ...

Discovering useful data like metadata and subject matter through the utilization of either a URL or the webpage itself alongside JQUery

Imagine you have a URL and you want to display information related to that URL on your webpage, similar to how Facebook or LinkedIn does. You input a URL and the website data is retrieved for display. I am working on an application using JQuery and HTML ...

Can we create an onFullscreen event handler for Power Bi Embedded?

I am currently working on creating a Report Component using React. I am looking to implement a functionality similar to the on() function in order to set up an event listener for when the report enters fullscreen mode. This way, I can pass a Function via ...

Adding the output of a callback function to a designated div or location?

I have integrated a JavaScript plugin called cordova-plugin-camera into my project and I am using it like this: camera.getPicture(successCallback, errorCallback, options) However, the issue I am facing is that whenever I trigger the plugin, it automatica ...

Activating the Play button to start streaming a link

Recently delved into the world of Ionic 4 and Angular, so definitely a beginner :) Purchased a UI Template from code canyon but didn't realize I needed to code the music player part. Been trying to get a music stream playing but no luck. Came across ...

How can you interact between a parent's named controller and JavaScript files in AngularJS?

Lately, I've been exploring the use of named controllers in my code and find it to be a much better alternative to using traditional $scope variables. It makes accessing parent controller attributes and functions within the DOM seamless. See an exampl ...

Revamp nested .map calls to utilize async/await pattern

Currently, I am working with a JSON file structured similarly to the example below: [ { "Item": "Item1", "ItemChild": [ { "Category": "Category1", ...

What are the best methods for integrating Django with html, CSS, and JS?

While creating my website, I discovered that Django is typically used for the backend while HTML, CSS, and JS are used for the front end. For now, I am focused on designing my pages using HTML, CSS, and JS and have not yet begun developing the backend. I ...

Change the color of a c3js chart when it loads

I have been searching for a way to customize the color of a scatter chart's plot, and I came across an example that uses d3 code within the chart http://jsfiddle.net/ot19Lyt8/9/ onmouseover: function (d) { d3.select(d3.selectAll("circle ...

Is the `document.documentElement` consistently defined and always representing the HTML element?

I am looking to make changes to the <html> element using a script within the <head> section of an HTML page. My goal is to only access and modify the <html> element itself, without affecting any of its children. Should I wait for the DOM ...