【问题标题】:Calling initialization function inside ng-repeat在 ng-repeat 中调用初始化函数
【发布时间】:2025-12-04 02:10:02
【问题描述】:

我试图在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>

ng-repeat函数里面的orderComment需要初始化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>'

在里面。

【问题讨论】:

  • 到底是什么问题?适合我:jsfiddle.net/330kedvq
  • 我在 ng-init 中注入 HTML。
  • 您不应该对ng-init 这样做。要么将 html 放在 div 中,要么使用自定义指令将 comment.stars 呈现出来。
  • 你可以为此创建一个“jsfiddle”吗?

标签: javascript angularjs angularjs-ng-repeat angularjs-ng-init


【解决方案1】:

一般来说,Angular 不鼓励自己对 DOM 进行更改,在这种情况下没有必要。

一个简单的解决方案可能是放入尽可能多的星星,并使用ng-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

【讨论】:

  • 你所有的解决方案都很好,我认为自定义指令是正确的方法。