javascript / angularjs concatenate String with number for loop

时间:2016-05-10 15:55:33

标签: javascript angularjs

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

我想用变量号做一个循环,以得到结果

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

变量$scope.test不是数组而是字符串

3 个答案:

答案 0 :(得分:1)

for (var i = 0; i < $scope.number; ++i) {
    $scope['test' + i] = date;
}

喜欢那个?

答案 1 :(得分:0)

我认为你低估或不了解数组和ng-repeat的目的。根据您的评论,听起来您希望能够遍历多组数据集,每组产生一个图表,并且我将使用您之前的评论作为许可来解决我认为您的< em>问题,而不是你的文字问题。

看看我制作的this example,对您自己的JSFiddle示例进行简单修改。我所做的就是将包含数据集的对象(我复制并调整你拥有的数据集)放入一个数组中,然后迭代它们,将数据传递给ng-repeat的图表(你可能需要)在视图窗格中向下滚动以查看第二个图表。

在你的JS控制器中:

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

在HTML视图中:

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

这基本上只是一个foreach循环。

答案 2 :(得分:0)

 $scope.chartDataArray = [];
for (var i = 0; i < 4; i++)// I replace "4" by variable which represent number of charts I need, I'm consuming Rest Api  
 {
  $scope.chartDataArray[i] = {
    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],// I replace it by my datas
    datasets: [{
      label: 'My First dataset',
      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: [65, 59, 80, 81, 56, 55, 40] // my datas
    }, {
      label: 'My Second dataset',
      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: [28, 48, 40, 19, 86, 27, 90] // my datas
    }]
  }; 
//scope.options ....
} //close the for

和我的HTML

 <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>