Combining a string with a number in a loop using JavaScript and AngularJS

var number = 0;  
var date = "2016-05-10"
$scope.test = date;

I am trying to create a loop using the variable number in order to achieve the following result:

$scope.test1 = 2016-05-10
$scope.test2 = 2016-05-10
$scope.test3 = 2016-05-10

The $scope.test variable is not an array but rather a string.

Answer №1

When iterating through the loop, for each number less than $scope.number, the code assigns the value of date to a variable named 'test' followed by the current index.

Is this what you were looking for?

Answer №2

It seems like you may not fully understand the potential of arrays and ng-repeat. Based on your description, it appears that you want to iterate through multiple sets of data to create charts. I'll take this opportunity to address what I believe is the underlying issue rather than just answering your specific question.

You can check out my version of your JSFiddle sample in this example. I've simply modified your code by placing the data set objects into an array and then using ng-repeat to pass the data to the charts (you might need to scroll down to see the second chart).

In your JavaScript controller:

// Chart.js Data
$scope.chartDataArray = [{
  labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
  datasets: [
    {
      label: 'My First dataset',
      // ... Color configurations
      data: [65, 59, 80, 81, 56, 55, 40]
    },
    {
      label: 'My Second dataset',
      // ... Color configurations
      data: [28, 48, 40, 19, 86, 27, 90]
    }
  ]
},{
  labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
  datasets: [
    {
      label: 'My First dataset',
      // ... Color configurations
      data: [0, 1, 2, 3, 4, 5, 6]
    },
    {
      label: 'My Second dataset',
      // ... Color configurations
      data: [12, 10, 8, 6, 4, 2, 0]
    }
  ]
}];

In your HTML view:

<canvas ng-repeat="data in chartDataArray" tc-chartjs-line chart-options="options" chart-data="data" auto-legend ng-click="chartClick($event)" chart="chart"></canvas>

This essentially functions as a foreach loop for creating the charts.

Answer №3

 $scope.chartDataArray = [];
for (var j = 0; j < 5; j++)// I replace "5" with a variable that represents the number of charts needed, consuming Rest Api  
{
  $scope.chartDataArray[j] = {
    labels: ['June', 'July', 'August', 'September', 'October', 'November', 'December'],// Replaced with custom data
    datasets: [{
      label: 'Dataset One',
      fillColor: 'rgba(220,220,220,0.2)',
      strokeColor: 'rgba(220,220,220,1)',
      pointColor: 'rgba(220,220,220,1)',
      pointStrokeColor: '#fff',
      pointHighlightFill: '#fff',
      pointHighlightStroke: 'rgba(220,220,220,1)',
      data: [30, 45, 60, 75, 50, 20, 35] // Custom data
    }, {
      label: 'Dataset Two',
      fillColor: 'rgba(151,187,205,0.2)',
      strokeColor: 'rgba(151,187,205,1)',
      pointColor: 'rgba(151,187,205,1)',
      pointStrokeColor: '#fff',
      pointHighlightFill: '#fff',
      pointHighlightStroke: 'rgba(151,187,205,1)',
      data: [15, 25, 35, 45, 55, 65, 75] // Custom Data
    }]
  }; 
//scope.options ....
} //closing the loop

and within my html document

 <div ng-repeat="data in chartDataArray">
  <canvas tc-chartjs-line chart-options="options" chart-data="data" auto-legend ng-click="chartClick($event)" chart="chart"></canvas>
 </div>

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

Raycasting intersections in Three.js

After successfully creating geometry and functions to manipulate it, I integrated them into a javascript UI library . However, I encountered a problem where the raycaster function was detecting intersections with geometry even when not directly under the m ...

There seems to be a contradiction in my code - I am returning a Promise but TypeScript is throwing an error saying that the

I currently have a function that retrieves a bot's inventory on the Frontend fetchBotInventory() { this.socket.emit('fetch bot inv'); this.socket.on('bot inv', (botInventory) => { return new Promise((resolve, re ...

Javascript - finding data in a table

I am new to the world of programming and currently learning javascript. I have a table with 754 values in the format 000089/04/18/0601AX. I am looking to create a script that will generate another table containing values with /04/18. Any assistance with ...

"An error occurred: Uncaught SyntaxError - The import statement can only be used within a module. Including a TypeScript file into a

I need to integrate an Angular 10 TypeScript service into a jQuery file, but I am facing an issue. When I try to import the TypeScript service file into my jQuery file, I encounter the following error: Uncaught SyntaxError: Cannot use import statement outs ...

jQuery code isn't functioning properly when I include the script using the complete URL

When I include the local jQuery like this, everything works fine: <script type="text/javascript" src="jquery-1.11.2.min.js"></script> However, when I try to link it from my server, things don't work as expected. I double-checked by openi ...

Is there a way for me to create a clickable link from a specific search result retrieved from a MySQL database using an AJAX

Currently, I am attempting to create an ajax dropdown search form that provides suggestions based on results from a MySQL database. The goal is for the user to be able to click on a suggestion and be redirected to the specific product. The code I am using ...

When integrating AngularJS $http with WordPress, the desired response may not always be achieved

I recently implemented a wp_localize_script for ajax in my WordPress project: wp_localize_script('cb_admin_js', 'cbAjax', array('ajax_url' => admin_url( 'admin-ajax.php' ))); As part of testing, I used an $http. ...

JavaScript code to verify if a checkbox is selected

Having some trouble making a text box value change based on checkbox status. I've attached a function to the onclick event of the checkbox, but it's not quite working as expected. <div> MyCheckbox <input type="checkbox" id="Check1" name ...

react-webcam npm package for optimizing video size

In my React app, I'm utilizing the npm package react-webcam. The <Webcam /> component is enclosed within a div with a dimension of {width: 100vw, height 100vh} I aim for the video element to adjust to the parent div's size and cover 100% ...

Unable to See Success Notification on First Attempt

I am facing an issue with displaying a message when adding a new record. The first time I add a record, the message shows up correctly. However, if I try to add another record, the message does not appear even though the record is added successfully. Here ...

There was an error: TypeError - The function collectionGroup cannot be called on the object _firebase__WEBPACK_IMPORTED_MODULE_10__.usersCollection.doc

I encountered an issue described above. Can someone help me identify what went wrong? My goal is to display all documents in the 'hives' collection. Is the code snippet shown in the second image correct? Or do I need to make some modifications? S ...

Enhancing AngularJS: Tailored iterations and data manipulations for more advanced grouping beyond basic ng-repeat limitations

Although I found the answer to this issue on Angular.js more complex conditional loops satisfactory and accepted it, I feel there is more to discuss. Let me provide further details that were not included in my initial inquiry. My goal is to transform the ...

Creating a dropdown button in HTML table cells with JavaScript: A comprehensive guide

I'm attempting to create a drop-down button for two specific columns in my HTML table, but all the rows are being converted into drop-down buttons. I only want the "categorycode" and "categoryname" columns to be drop-down. $(document).ready(functio ...

Using the Angular Array Element to Retrieve the HTML Class Name

I have a unique Angular array that holds JSON data. Among the elements is the name of an ionic icon. I'm utilizing ng-repeat to iterate through the elements and aim to dynamically change the ionic icon's name with each iteration. <div class = ...

Input various information into a single form multiple times and automatically submit it to a Google spreadsheet

I have some data that needs to be transferred to an array and then sent to a Google Sheet. The data looks like this: -|PO: 2005 | 12121211212121,| Qty: 45| BIN:110| eBay| 11/6/2017-| PO: 2165 | 333333333,| Qty: 54| BIN:20| google| 11/6/2017- First, I use ...

Having trouble connecting retrieved database information with AngularJS for display in the view

I am currently working on extracting data from a database and displaying it in a view using AngularJS. I have created a WEM method for this purpose: [WebMethod] public static string fetchNames() { SqlHelper sql = new SqlHelper(); DataTable dt = sql.Ex ...

Find the smallest number within an array without relying on the Math function

Could someone assist me in creating a function that finds the lowest number in an array? I've been struggling with this and previous answers on similar questions didn't really help as they presented solutions with unfamiliar code. The current cod ...

Is it possible for parameters to still be filled even when they start off empty

Currently, I am enrolled in a javascript course and struggling to comprehend how the parameter in my example below is populated with the "correct stuff" without actually calling the function with a corresponding element? success: function(result) { ...

What steps can be taken once the browser has completed all rendering processes?

I have a large form that functions on older PCs. This form is a component of a thin client system and is implemented using AngularJS to create a Single Page Application. One of the tabs on the SPA includes this form. Upon opening the form, requests are se ...

"jQuery's input type property is not functioning properly when attempting to append new

I am facing an issue with my dynamic table structure and the add row option. Whenever I click on add, a new row is created. However, the problem arises when the $("[name*=vehicle_type]").change(function () does not work for appended input fields. It only ...