【问题标题】:angular $index numbering with condition in ng-repeat & ui-sortable在 ng-repeat 和 ui-sortable 中有条件的角度 $index 编号
【发布时间】:2014-08-21 13:36:58
【问题描述】:

我正在尝试在列出数组中的所有项目时实现自定义编号。

数组中的所有项目都使用 ng-repeat 和 ui.sortable 呈现。

编号必须以这样一种方式完成,对于数组项“语句”,不应增加和显示计数。否则我可以使用 $index 而不是外部计数。

对于任何其他数组项,应增加计数并显示。

让我得到最接近结果的解决方案是我将 $index 传递给编写在控制器中的过滤器函数。

类似于 HTML:

<li ng-repeat="question in questions">

<div class="no"> {{ filterIndex(question.question, $index) }} </div>
<div>{{question.question}}</div>

</li>

在控制器中:

    var filterValue = 0;

    $scope.filterIndex = function (value, count) {

        if (count === 0) {
            filterValue = 0;
        }

        if (value !== 'statementText') {
            filterValue = filterValue + 1;
            return filterValue;
        }
        else {
            return '"';
        }

    };

即使它运行时没有任何错误,从函数返回的计数也不会更新,就像我们使用 ui-sortable 更新订单时使用 $index 获得的一样。

在这里查看:js-fiddle using filter function

的意思是,一旦它在中渲染了(4),即使我们通过拖动将它移动到顶部或底部,它也将保持不变。

我尝试了不同的方法,几乎​​所有事情都以“超出最大迭代限制。”告终。 实际场景有点复杂,因为它包含嵌套的 ng-repeats 和类似的计数,在子循环中交替使用数字和数字。

这里是重新开始的链接: js-fiddle

【问题讨论】:

标签: angularjs angularjs-ng-repeat angular-ui jquery-ui-sortable angular-filters


【解决方案1】:

你可以把它注入你的控制器,它会监听数组的变化,并更新索引:

  var update = function(){
      var currentCount = 0;
      var questions = $scope.questions;
      for(var j = 0; j < questions.length; j++){
          if(questions[j].question != null){
              if(questions[j].question.indexOf("statement") < 0){
                  questions[j].calculatedIndex = ++currentCount;
              }
          }
      }
  };

  $scope.$watchCollection('questions', function(){
    update();      
  });

  update();

可能需要进行一些微调,因为我没有完全专注于您的问题。在 ng-repeat 中,您现在可以访问计算索引。声明项目将为“NULL”,您可以使用 ng-show 。

【讨论】:

  • 哦!那很简单!感谢您提供确切的解决方案!我应该停止让事情变得复杂!
【解决方案2】:

尝试添加额外的选项:

ng-init='question.index = $index+1'

http://jsfiddle.net/ny279bry/

【讨论】:

  • 能否请您看一下问题中突出显示的区域。我认为我们处于不同的极点。
猜你喜欢
  • 2013-08-06
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-21
  • 2014-03-25
  • 1970-01-01
  • 2017-11-24
  • 1970-01-01
相关资源
最近更新 更多