【问题标题】:how can I re-draw ng-repeat when changes to an array are made?对数组进行更改时,如何重新绘制 ng-repeat?
【发布时间】:2016-01-14 22:44:47
【问题描述】:

我有一个对象数组,每个对象的数据可能略有不同。我在选择要显示的正确指令的指令上使用 ng-repeat。该“显示”指令获取对象并以正确的格式显示数据。这一切都很好。

现在我需要重新组织数组的顺序。当我更新数组时,“显示”指令不会重新排序,只有数据会发生变化。例如,大多数数据集都有一个“标题”字段,所以那些更新,但“显示”没有。

如何最好地刷新 ng-repeat 以便它正确地重新排序“显示”指令?

我可以发布代码,但我觉得这更像是一个概念性问题。

HTML:

 <module-builder module="{{$index}}" ng-repeat="module in build.modules track by $index"></module-builder>

模块构建器:

    (function() {
    'use strict';

    angular
        .module('app.email_editor')
        .directive('moduleBuilder', moduleBuilder);

    function moduleBuilder ($compile) {
        var directive = {
            link: link,
            restrict: 'EA'
        };
        return directive;

        function link(scope, element, attrs) {
            var module = scope.build.modules[attrs.module];
            var template = '';
            switch (module.Name){
                case 'moduleTypeOne':
                    template = "<module-type-one class='{{module.Class}}'></module-type-one>";
                    break;
                case 'moduleTypeTwo':
                    template = "<module-type-two class='{{module.Class}}'></module-type-two>";
                    break;
                default:
                    break;
            }
            element.html(template);
            $compile(element.contents())(scope);
        }
    }

})();

数据样本:

顺便说一句,html5Sotable 是重新排序的接口

【问题讨论】:

  • 你能提供一些示例代码吗? documentation 表示When items are reordered, their respective templates are reordered in the DOM. 也许你还需要在表达式中使用track by
  • 由于 Angular 的双向绑定特性,这实际上是一个实现问题,而不是概念问题。有内置的过滤器可以完美地管理对象的顺序,但是角度文档提到“您需要注意 JavaScript 规范没有定义为对象返回的键的顺序。”目前尚不清楚您是重新排序数组中的对象,还是只是重新排序对象的键。
  • 在第二段中提到,模板不会重新排序,只有数据会。我会准备代码。
  • 通过使用 $compile 重新编译您想要重新排序的部分?
  • 嗯,第一件事是$index 不是数组中项目位置的表示,它只是ng-repeat 分配的任意值。因此,如果您使用 $index 值来尝试从数组中找到要使用的正确模板,您将无法获得预期的结果。

标签: javascript arrays angularjs angularjs-directive angularjs-ng-repeat


【解决方案1】:

$index 中出现问题,在这种情况下,在 $index 更改时重新渲染元素。
因此,如果您的数组中确实有重复项,则应该通过其他方式对其进行跟踪。

【讨论】:

  • 好的,所以如果我在服务器端跟踪,生成 uid...很好奇,我会试一试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-16
  • 1970-01-01
  • 1970-01-01
  • 2013-06-24
  • 1970-01-01
  • 2013-05-23
相关资源
最近更新 更多