AngularJS:基于变量计数输出HTML

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AngularJS:基于变量计数输出HTML相关的知识,希望对你有一定的参考价值。

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

以上是关于AngularJS:基于变量计数输出HTML的主要内容,如果未能解决你的问题,请参考以下文章

将变量传递到 Ionic Framework 页面(基于 AngularJS)

在并行位片代码中实现快速计数器

如何Angularjs1.3在页面中输出带Html标记的文本

嵌套 ng-repeat 的 AngularJS 记录计数

将带有HTML标签的输出从AngularJs传递到HTML [重复]

angularJs 学习笔记