AngularJS:基于变量计数输出HTML

时间:2019-01-18 22:41:41

标签: javascript angularjs

我有一个数组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); 
  }
}

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

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