【问题标题】:DOM keeps being rebuilding with angular-selectize ng-repeat and track byDOM 通过 angular-selectize ng-repeat 和 track by 不断重建
【发布时间】:2023-03-29 15:00:02
【问题描述】:

我将 AngularJS 与 angular-selectize 模块一起使用。

要使用我需要的元素填充页面,我使用如下内容:

index.html

<selectize
    ng-repeat="select in selects_data track by $index"
    config="selectizeConfig"
    options="select.options"
    ng-model="selects_models[select.name]">
</selectize>

controller.js

$scope.update_data = function(){
    //I'm using AngularJS resource to get the JSON data from the server
    $scope.selects_data = StatesTableControl.get({'path': $scope.element.path},
        function(data){
            //Success
            angular.forEach(data, function(item){
                $scope.selects_models[item.name] = item.current_id
            });
        }, function(error){
            //Error
        }
    );
};

$scope.update_data();
$interval($scope.update_data, 3000);

无论我使用track by $indextrack by select.name还是根本不使用,每次使用从服务器获取的数据更新selects_data数组时,所有&lt;selectize&gt;&lt;/selectize&gt;元素都会完全重绘, 即使更新后数组内容相同。

我还没有找到任何方法来自己解决它。 而且我不明白为什么当我在 div 或其他元素中使用 track by 时,它会起到同样的作用。

如果有人可以帮助解决这个问题,我会非常高兴!

【问题讨论】:

  • 你能粘贴负责更新selects_data的代码吗?
  • @ConstantinePoltyrev 我扩展了我的问题中的代码示例,我希望它有助于澄清我的应用程序中发生了什么。

标签: javascript angularjs angularjs-ng-repeat angularjs-track-by


【解决方案1】:

我认为这与您跟踪项目的方式没有任何关系。如果StatesTableControl.get 每次调用它都返回新对象,我认为 Angular 认为它们是不同的对象,即使它们包含相同的数据。

您可以只发送已更改的对象,或维护对象的版本号,以便您了解未更改的对象并且无需替换它们。

【讨论】:

  • 感谢您的回复。当我使用不带“track by”选项的“ng-repeat”时,每次源对象或数组更改时,DOM 元素都会重新构建。但是如果我使用 'track by $index' 选项,DOM 只会在新元素出现或旧元素消失时发生变化。它适用于 '
    ' 等其他 html 元素,但不适用于 '' 元素。我只是不明白为什么。
猜你喜欢
  • 1970-01-01
  • 2018-03-18
  • 2014-02-20
  • 2015-06-18
  • 1970-01-01
  • 2014-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多