Angular - 无限的摘要循环

时间:2016-02-24 11:45:54

标签: angularjs

我目前面临无限的摘要循环错误,我需要一些帮助/建议。

所以我已经阅读了the docs以及StackOverflow上的帖子,我想我理解这个问题 - 如果有人也可以确认 - 这主要是因为$scope中的某些内容正在改变很多次。

假设我上面所理解的是正确的 - 我不确定如何解决这个问题,我们将不胜感激。

我的代码如下:

HTML Side

<ul class="no-bullet" ng-repeat=“person in persons”>
   <li>
     <div class="progressBar" ng-style="{background: styleBuilder(person.options)}"></div>
   </li>
</ul>

在我的控制器中 (对于上下文:personsArray是从HTML端传递的内容,而for循环用于将包含数字的数组更新为百分比,因此['classA: 8', 'classB: 2']变为['classA: 75', 'classB: 25'](我已经测试了这个并且它有效)

  $scope.styleBuilder = function (optionsArray){

    for (var index in personsArray){
      proportion = parseInt(personsArray[index].split(':')[1])/sumOfAllValues;
      if (isNaN(proportion) ){
        proportion = 0;
       }

       personsArray[index] = personsArray[index].substring(0, personsArray[index].indexOf(':'));
       personsArray[index] = personsArray[index] + ' : ' + proportion*100;

    }

}

感谢。

2 个答案:

答案 0 :(得分:2)

问题在于这一行(在@Raulucco解释的摘要周期中):

ng-style="{background: styleBuilder(person.options)}"

尝试ng-init:

<li ng-init="bg = styleBuilder(person.options)">
   <div class="progressBar" ng-style="{background: bg}"></div>
</li>

答案 1 :(得分:1)

问题是您在循环遍历数组的同时更改了数组中的元素。 Angular将监视绑定到每个选项属性,因为您正在访问循环内的属性,您更改它会触发摘要循环。 要避免在此示例中,请不要更改options属性,只需返回新样式或循环遍历数组,并在将选项分配给$ scope之前更改选项。

相关问题