[英]Calling initialization function inside ng-repeat
我正在尝试在ng-repeat
调用ng-init
函数,它仅在第一个元素上起作用:
<li ng-repeat="comment in ad.comments|limitTo:quantity | orderBy : sortComment : true">
<div id="starsDiv" ng-init="orderComment(comment.stars)"></div>
Comment: {{comment.text}}
<cite class="clearfix"> on {{comment.posted | date}}</cite>
</li>
该orderComment
里面ng-repeat
功能需要给init starDiv
:
$scope.orderComment= function(numOfStars){
var html = '<i class="fa fa-star-o" style="color:gold;"></i>';
for(var i =0 ; i<numOfStars-1;i++)
{
html += '<i class="fa fa-star-o" style="color:gold;"></i>';
}
document.getElementById("starsDiv").innerHTML = html;
};
通过comment.stars
的值将HTML注入starsDiv
。 例如,如果注释等于4,则将有以下4个HTML元素:
'<i class="fa fa-star-o" style="color:gold;"></i>'
在里面。
通常,Angular不建议您自行更改DOM,在这种情况下,没有必要。
一个简单的解决方案可能是放入尽可能多的恒星,然后使用ng-show
show仅显示我们需要的数量。 假设有5星:
<i class="fa fa-star-o" style="color:gold;" ng-show="comment.stars > 0"></i>
<i class="fa fa-star-o" style="color:gold;" ng-show="comment.stars > 1"></i>
<i class="fa fa-star-o" style="color:gold;" ng-show="comment.stars > 2"></i>
<i class="fa fa-star-o" style="color:gold;" ng-show="comment.stars > 3"></i>
<i class="fa fa-star-o" style="color:gold;" ng-show="comment.stars > 4"></i>
如果您需要常规解决方案,则可以始终使用ng-repeat
。 您只需要一个将接受数字并返回该大小的数组的函数。 您可以像这样使用数组。
<i class="fa fa-star-o" style="color:gold;" ng-repeat="x in array(comment.stars)"></i>
一个更通用的解决方案是创建一个渲染这些星星的自定义指令。 我建议阅读有关自定义指令的内容: https : //docs.angularjs.org/guide/directive
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.