Can the variable name be customized according to the input given?

My goal is to create multiple columns with randomized results independently of each other, based on user selection. I am not sure how many columns there will be, and I want the function to be repeatable as needed. While I know how to achieve this in PHP (using something like $var{$i}), I am unsure about how to do it in Angular.

This is how the HTML looks:

<tr>
  <td><button ng-click="rollDice1(1)">rand 1</button></td>
  <td><button ng-click="rollDice2(2)">rand 2</button></td>
  <td><button ng-click="rollDice3(3)">rand 3</button></td>            
</tr>
<tr>
  <td>{{animal1}}</td>
  <td>{{animal2}}</td>
  <td>{{animal3}}</td>
</tr>

In my controller, I currently have separate functions for each column (e.g., rollDice1, rollDice2) which result in repetitive code. Each function generates random values for different variables. What I would like is to have a single function where the variable name changes based on input, but I haven't been able to make it work. Here's what I've tried:

$scope.rollDice = function (val) {
   $scope.animal[val] = animalRand();
   $scope.color[val] = colorRand();
   $scope.size[val] = sizeRand();
   $scope.age[val] = randFloor(15, 1);
};

I attempted variations like $scope.animal.val and even $scope.animal{val}, but these resulted in errors. Is there a way to achieve what I'm looking for, or do I have to stick with creating separate functions for each column?

You can check out the Plnkr here: http://plnkr.co/edit/J0mYup?p=preview

Thank you for your help!

Answer №1

To access the array, you should use array accessor notation with a string key that is generated from the value itself. Modify your rollDice function as follows:

$scope.rollDice = function (val) {
   $scope["animal" + val] = animalRand();
   $scope["color" + val] = colorRand();
   $scope["size" + val] = sizeRand();
   $scope["age" + val] = randFloor(15, 1);
};

After this modification, you can call the function using rollDice(1), rollDice(2), and so on in your template code.


If there are numerous such instances, it might be more efficient to store the data in an array. You can initialize an array on the scope like this:

$scope.data = [];

Subsequently, update your rollDice function to the following structure:

$scope.rollDice = function (val) {
   $scope.data[val] = {
       animal: animalRand(),
       color: colorRand(),
       size: sizeRand(),
       age: randFloor(15, 1),
   };
};

The way to invoke rollDice remains the same, but you now have to access the scope data differently in the HTML template.

<tr>
    <td>{{data[1].animal}}</td>
    <td>{{data[2].animal}}</td>
    <td>{{data[3].animal}}</td>
</tr>

This approach offers the additional benefit of automation through features like ngRepeat. For instance, the code snippet can be simplified to:

<tr>
    <td ng-repeat="item in data">{{item.animal}}</td>
</tr>

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

Challenges with CSRF tokens in Express

I am struggling to set up CSRF protection using csurf and express. My application utilizes Angular on the front end, so I believed that adding the following to my app would suffice: app.use(cookieParser('test secret')); app.use(cookieSession({ ...

Using Grails to create remote functions with multiple parameters

Currently, I am able to send one parameter to the controller using the code snippet below in Javascript: <g:javascript> var sel = "test"; <g:remoteFunction action="newExisting" method="GET" update="updateThis" params="'sel='+s ...

Utilize JavaScript to redirect based on URL parameters with the presence of the "@ symbol"

I need help redirecting to a new page upon button click using a JS function. The URL needs to include an email address parameter. <form> <input type="email" id="mail" placeholder="ENTER YOUR EMAIL ADDRESS" requir ...

Unable to adjust the width of the react-select component

I've been struggling to adjust the width of the select element but no matter what I try, it remains at a default width of about 75px. const CustomContainer = styled('div')` width: 100%; height: 100%; display: flex; flex-flow: row wr ...

How can I utilize an external file in Node js to output as a response?

I came across a similar inquiry, but I am interested in exploring manual methods. My goal is to achieve this without relying on express or any other external library. var http = require('http'); var server = http.createServer(function(req, res) ...

Enhancing JSON Objects in AngularJS with Custom Properties and Calculations

Hello, I'm still getting the hang of angularjs and could use some guidance. I have a Rest service that provides data on saleItems when a get request is made, as shown below: saleItems = [ { "id": 236, "variant": "Oval Holder", "mrp": "6 ...

Implementing an ajax search functionality

I am currently working on implementing an AJAX search feature into my project. The application initially displays all client data in a table on the webpage. When something is typed into the search bar, I want the search results to be shown instead of all ...

Assign a value to a dropdownlist in Javascript

I am facing an issue with setting the selected value of a dropdownlist that is populated by a webservice using ajax cascading dropdown. It seems like the values are not available when the javascript code runs, even though I have placed it at the bottom o ...

Having issues debugging in the browser as React seems to be undefined

I am trying to implement a Context system to store the login user's name and use it for protected routes. context.js import React from 'react'; const axios = require('axios'); export const AuthContext = React.createContext(null); ...

Manipulate HTML injected in real-time to adjust size within a preview container using Angular-UI

Within my Angular-UI modal view, I have a preview feature: <div class="wrapper bg-white b-b ng-binding" ng-bind-html="item.content" style="overflow:auto"></div> Currently, I am using style="overflow:auto" to show scroll bars when the inserted ...

"Utilize Angular to inject a module into several different modules simultaneously

I'm trying to load a module called userFromServer on my base html page. My goal is to inject it into both the main app module and the mixpanel module. However, I'm encountering an injection error when I attempt to inject userFromServer into analy ...

How to end a test case in Protractor when a specific element has a certain value

Currently wrapping up a suite of tests in Protractor, but running into an obstacle with a common task. I need to check if a textbox contains a value and terminate the test case with a failure if it does. (If the textbox is not empty, the test case is bound ...

Combining two geometries with indexes into a BufferGeometry

Currently, I am utilizing a fixed set of data that contains indices, vertices, and colors, along with multiple instances of THREE.Geometry to populate a scene with objects. This process is quite slow, as it involves adding and removing numerous objects at ...

Issue with Struts 2 tag causing malfunction in validating the collection

When iterating through a list in a JSP file using Struts 2 tags, the code below is used: <%@ taglib prefix="s" uri="/struts-tags"%> <head> ... The issue arises with date validation. The following line of code does not work: <td><s:d ...

What is the method for initiating a POST request in Java Script without including any data?

Currently, I am utilizing Ajax to send an array to the router, as demonstrated below... var send = function () { var data = search console.log(data) $.ajax({ type: 'post', url: ...

Is there a way for me to receive numerical values instead of NaN?

I'm currently facing a challenge in creating a Fibonacci number generator and I've hit a roadblock. It seems like I have a solution, but the appearance of NaN's is causing me some trouble. function fibonacciGenerator (n) { var output = [ ...

MongoJS Node findOne query inaccurately returns empty result set

Utilizing MongoJS: https://github.com/mafintosh/mongojs Retrieves all data Returns an empty array</p> The database contains the data I am looking for. I've also tried searching using a different key (such as name). Why is it unable to locate ...

When it comes to optimizing JavaScript, what is the best approach for replacing multiple substrings in a string with various strings?

While working on the code I develop and maintain, I encountered an issue. There is a function in my code that takes a query (in the form of a string) and replaces certain substrings within that string with different ones. For instance, if a user inputs th ...

Working with nested arrays in Mongoose/Javascript: Adding an Object to an Array within another Array

I have been attempting to add an object to an array that is nested inside another Array in Mongoose. Essentially, it's like having comments for the comments. Below is the structure of my schema: const Schema = new mongoose.Schema ({ name: {type: Str ...

Troubleshooting Problem with Parsing Float in Angular

Currently, I am facing an issue while using a filter to calculate totals from dynamic data in ng-repeat. The problem lies in my inability to limit the decimals to 2 places. Below is the code snippet of my filter: app.filter('sumByKey', function( ...