我有一个数组slides,其中包含变量stars。我需要在每张幻灯片上获取stars的值,然后使用该数字为每张幻灯片重复HTML字符串。

我可以得到stars的值,但是它会遍历所有6张幻灯片,并提供其值6次。

我只需要获取stars的所有值一次。

var slides = [
{
  'text' : 'The staff was fantastic and very friendly. I would definitely recommend them to anyone. The care has been great!! - ONLINE REVIEWER',
  'stars' : 4
},
{
  'text' : 'The staff was fantastic and very friendly. I would definitely recommend them to anyone. The care has been great!! - ONLINE REVIEWER',
  'stars' : 3
},
{
  'text' : 'The staff was fantastic and very friendly. I would definitely recommend them to anyone. The care has been great!! - ONLINE REVIEWER',
  'stars' : 2
},
{
  'text' : 'The staff was fantastic and very friendly. I would definitely recommend them to anyone. The care has been great!! - ONLINE REVIEWER',
  'stars' : 1
},
{
  'text' : 'The staff was fantastic and very friendly. I would definitely recommend them to anyone. The care has been great!! - ONLINE REVIEWER',
  'stars' : 5
},
{
  'text' : 'The staff was fantastic and very friendly. I would definitely recommend them to anyone. The care has been great!! - ONLINE REVIEWER',
  'stars' : 2
}
];

$scope.addStars = function(){
  i = 1;
  for (i=1; i<slides.length; i++) {
    var starsCount = slides[i].stars;
    var starsHTML = '<a href="#">☆</a>';
    starsFinal = starsHTML.repeat(starsCount);
    console.log(starsFinal);
  }
}

最佳答案

您可以执行以下操作:

$scope.slides = [
{
  'text' : 'The staff was fantastic and very friendly. I would definitely recommend them to anyone. The care has been great!! - ONLINE REVIEWER',
  'stars' : 4
},
{
  'text' : 'The staff was fantastic and very friendly. I would definitely recommend them to anyone. The care has been great!! - ONLINE REVIEWER',
  'stars' : 3
},
{
  'text' : 'The staff was fantastic and very friendly. I would definitely recommend them to anyone. The care has been great!! - ONLINE REVIEWER',
  'stars' : 2
},
{
  'text' : 'The staff was fantastic and very friendly. I would definitely recommend them to anyone. The care has been great!! - ONLINE REVIEWER',
  'stars' : 1
},
{
  'text' : 'The staff was fantastic and very friendly. I would definitely recommend them to anyone. The care has been great!! - ONLINE REVIEWER',
  'stars' : 5
},
{
  'text' : 'The staff was fantastic and very friendly. I would definitely recommend them to anyone. The care has been great!! - ONLINE REVIEWER',
  'stars' : 2
}
];

$scope.addStars = function(startCount) {
  return Array(startCount).fill().map(function() {
    return '<a href="#">☆</a>';
  }).join('');
}

<div ng-repeat="slide in slides">
  <div ng-bind-html="addStars(slide.stars)"></div>
</div>

关于javascript - AngularJS:基于变量计数输出HTML,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54262355/

10-09 23:42