Produce a consistent random number every time the controller is initialized

I currently have an Icon and a unique scope.id, where I assign a different color code to the Icon each time. This is what I have:

angular.module('myAppp').controller('myCtrl',function(){
    scope.id=[0,1,2,3];
    //generate random number
    $scope.Icon=[];
    for(i=0;i<scope.id.length;i++) {
        var ran= Math.floor( Math.random()*255)+$scope.id[i];
        $scope.Icon.push(ran);
    }   
});

Here's the HTML:

<div ng-repeat='id in id'>
    <span style="background-color:rgb({{$scope.Icon[$index]}},255,255)">{{id}}</span>
</div>

Whenever I reload the page, I want the colors to remain the same, but due to the use of Math.random(), they change. Can someone provide guidance as I'm new to this?

Answer №1

If you want to save the current value, consider utilizing cookies.

Upon page load, make sure to check for an existing cookie and if none is found, generate a random value and create a new cookie.

Whenever the color changes, update the cookie with the new value. This way, every time the user revisits the page, the stored color will be applied.

To learn more about implementing cookies in angularjs, refer to this example:

Answer №2

The seed for the random number generation algorithm is automatically determined and cannot be adjusted by the user

Source: JavaScript documentation.

Utilize a pre-existing array of numbers for efficiency.

Answer №3

Check out this demonstration showcasing dynamic color change upon page load: http://fiddle.jshell.net/xopddsxp/

HTML:

<div ng-app="myAppp" ng-controller="myCtrl">
    <div ng-repeat='id in id'>
        <span style="background-color:rgb({{Icon[$index]}},{{Icon[$index +1]}},{{Icon[$index + 2]}})">{{id}}</span>
    </div>
</div>

JS:

var app = angular.module("myAppp", []).controller('myCtrl',function($scope, $http){
     $scope.id = [0,1,2,3]; //generate random number
     $scope.Icon=[];
     for(i=0; i < $scope.id.length; i++){  
       var ran= Math.floor( Math.random()*255)+$scope.id[i];
       $scope.Icon.push(ran);
     }  
});

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

Troubleshooting Controller Action Failure in AJAX Request

Hello there I am encountering an issue with my AJAX call not reaching the Controller action in my ASP.NET MVC web application project. Below, you will find my AJAX call written in Javascript and the corresponding Controller's Action. Here is the AJA ...

Unraveling functions from a JavaScript promise in a web application using ExpressJS and NeDB

I have successfully implemented code that retrieves all users from my neDB-promisses: const fetchAllUsers = (res) => { db.find({}) .sort({ name: 1 }) .exec() .then( (content) => { res.status(2 ...

Version 5.0.4 of Mui, when used with makeStyles and withStyles, is experiencing issues with applying styles to Mui

I've been diving into a react project using Mui v5.0.4 and encountered an unexpected issue with my custom styles. Initially, everything was functioning smoothly, but suddenly the styles I had defined were no longer appearing as intended in components ...

When attempting to scrape data from Whole Foods products using Python and selenium, I encountered an issue

After using the following code, I received this output: driver = webdriver.Chrome('/full/path/to/chromedriver') Product Name: USDA INSPECTED BEEF RIBEYE STEAK* Product Price: I am puzzled as to why the product price is empty when it should b ...

Error: The function cannot be applied to req.body

I am designing a feature to calculate the total nutritional value of selected food items from a table. Users can input the quantity for each food item and choose which items to include using checkboxes. The program will multiply the quantity by the nutri ...

The optimal method for loading CSS and Javascript from an ajax response within a JavaScript function - Ensuring cross-browser compatibility

I am in a situation where I need jQuery to make sense of an ajax response, but due to latency reasons, I cannot load jQuery on page load. My goal is to be able to dynamically load javascipt and css whenever this ajax call is made. After reading numerous a ...

Leverage Node.js/Express backend objects within frontend JavaScript

I'm new to programming and feeling a bit lost. I've been struggling to find a solution for my issue despite spending a lot of time searching. Currently, I am working on coding a prototype for a simple web app using Node.js, Express, MongoDB, and ...

stop the page from refreshing when clicking on the map area

http://jsbin.com/iTeNiJIt/1/edit?output I currently have multiple map areas on my webpage. When a user clicks on any of these areas, I want to create an animation without refreshing the page. However, I am facing an issue where the page refreshes every ti ...

Unexpected display issues with CSS shapes in Bootstrap framework

Been experimenting with creating custom shapes in Bootstrap - they display correctly in HTML and CSS, but Bootstrap distorts them. It seems like there are no conflicting classes. Could it be necessary to use '!important' on some of the elements? ...

Adapt the dimensions of the iframe to perfectly match the content within

Looking for a way to dynamically adjust the size of an iframe to perfectly fit its content, even after the initial load. It seems like I'll need some kind of event handling to automatically adjust the dimensions based on changes in the content within ...

Permit a high volume of pop-up notifications

I created an automation process to shut down all computers in a network using a combination of HTML and PowerShell. The HTML page displays a list of PCs with checkboxes next to each one for selection, as well as a "shutdown" button. In my JavaScript code, ...

Removing exclamation points from the routing of a state URL is a key aspect of mastering full stack development

Is there a way to remove exclamation marks from the url in state routing using mean.io? Currently, my url looks like http://localhost:3000/#!/auth/register I just want to get rid of the "!" marks after the "#" symbol. Is it possible? Here is the content ...

Terminate the npm build script within a Node.js script

I have developed a node script that checks for the presence of a lock file in my project. If the lock file is not found, I want to stop the npm build process. Any suggestions on how to achieve this? lock-check.js const path = require('path'); c ...

Exploring the history and present state of Vue lifecycle hooks

Is there a way to access previous and current data in the updated lifecycle hook in Vue, similar to React? I want to be able to scroll a list of elements to the very bottom, but for this I need: The already rendered updated DOM (to calculate the scroll) ...

Utilizing AngularJS to Incorporate CSV Data into SVG Illustrations

My latest project involves creating a floor plan application for my company using SVG floor plan drawings from Adobe Illustrator CC, along with HTML, CSS, and AngularJS. The goal is to combine a floor plan with static cubicle/office numbers with a CSV fil ...

Adding data to a pre-made JavaScript file template to create a fresh document

In my web application, I have a form with multiple inputs: <form action=""> Title1:<br> <input type="text" name="title1"> <input type="text" name="title1Description"> <br> Title2:<br> <input t ...

Sending information from the Controller to a JavaScript function

Within my controller, the following code is present: public async Task<IActionResult> Index() { HttpResponseMessage responseMessage = await _httpClient.GetAsync(_getDataControlerApiUrl + "/getUserData"); string stringDat ...

Is WebStorm with Node Supervisor being utilized to eliminate the need for restarting after every code modification?

Currently, I am utilizing WebStorm as my node IDE and have found it to be quite impressive. However, one issue I am facing is figuring out how to incorporate node supervisor into my workflow within WebStorm. Has anyone successfully managed to set this up ...

The PHP Include function seems to be malfunctioning and unable to properly display

Everything you see is what I have on my home.php page <?php include ('../bgs/bg-verbier.html'); include('../menus/menu-verbier.html'); ?> Both of the files requested are located in the parent directory. The /menus/menu-v ...

function executed when meteor template finishes loading all content

Here is a template structure that I am working with: <template name="mainEvents"> <section class="main-events-list events-list js-content-slider"> {{#each events}} <div class="events-list-item"> &l ...