首页 > 解决方案 > AngularJS:基于变量计数输出 HTML

问题描述

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

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

我只需要获得stars1 次的所有值。

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="#">☆&lt;/a>';
    starsFinal = starsHTML.repeat(starsCount); 
    console.log(starsFinal); 
  }
}

标签: javascriptangularjs

解决方案


你可以这样做:

$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="#">☆&lt;/a>';
  }).join('');
}

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


推荐阅读