【问题标题】:Angular ng-repeat causes flickeringAngular ng-repeat 导致闪烁
【发布时间】:2014-07-31 10:49:15
【问题描述】:

我正在显示带有此代码的缩略图列表:

<div class ="channel" ng-repeat ="channel in UIModel.channels" ng-class ="{evenchannel: ($index % 2) == 0, oddchannel: ($index % 2) == 1}">
            <img class="channel-img" ng-src ="data/channels/{{$index + 1}}/thumb"/>
</div>

在控制器中,我有一个获取新缩略图图像的 ajax 请求。因此,Angular 会更新图像但会导致闪烁。有没有办法在更新DOM的过程中双缓冲或不删除列表?

【问题讨论】:

    标签: javascript html angularjs angularjs-ng-repeat


    【解决方案1】:

    按照@cexbrayat 的回答,如果您没有任何ID,您也可以将其与track by $index 关联。这是 ng-repeat 期间的内部迭代 #。

    <div ng-repeat="channel in UIModel.channels track by $index"></div>
    

    【讨论】:

    • 旧答案,但即使在今天也对我有用。 “track by $index”如何解决闪烁问题?
    • 它使用内部哈希而不是动态创建一个,这会导致渲染速度变慢,从而闪烁:) @codemax
    • 为我工作。但缓存页面加载缓慢。
    • 最初工作。但是正如@tyuo9980 在下面的另一条评论中指出的那样,这阻止了dom 更新!
    【解决方案2】:

    您可以在 ng-repeat 中使用带有唯一标识符的 track by。如果我想你的频道对象有一个 id,你可以这样做:

    <div class ="channel" ng-repeat="channel in UIModel.channels track by channel.id"></div>
    

    跟踪避免了每次更新时完整的 DOM 删除和重新创建,因为 Angular 将能够跟踪元素是否与以前相同并保留 DOM 元素。

    【讨论】:

    • 我使用了 $index 实现,但现在我的缩略图根本没有更新。我有另一个显示时间和更新的属性。
    【解决方案3】:

    首先尝试@Mark Pieszak 和@cexbrayat 的答案,但是如果您在应用程序中使用ngAnimate,它们可能无法完全解决您的问题。

    除了:

    <div class="channel" ng-repeat="channel in UIModel.channels track by channel.id"></div>
    

    我需要添加以下 CSS 来禁用此 ng-repeat 的动画:

    .channel .ng-leave, .channel .ng-leave-active {
        display: none !important;
    }
    
    .channel .ng-move, .channel .ng-move-active {
        display: none !important;
    }
    

    这样可以确保一旦动画开始,该项目就会立即隐藏。替代方法是实际使用动画,或者在代码中使用 $animate.enabled('div.channel', false); 禁用元素上的动画。

    【讨论】:

      【解决方案4】:

      我遇到了同样的问题,使用 $index 的曲目终于为我解决了这个问题。起初我不认为是这样,因为我直接在另一个 ng-repeat 所在的图像标签中使用了它。一旦我将它放在 ng-repeat 上的父 div 中(以及)它就起作用了:

      <div ng-repeat="item in blah track by $index">
         <!-- stuff -->
         <!-- later in this div: -->
         <img data-ng-repeat="dict in item.blah track by $index" class="smallPics ng-cloak" src="{[dict.path]}"></img>
      
         <!-- and the rest is blah-istory -->
      

      【讨论】:

        【解决方案5】:

        作为说明:

        如果使用 track by $index 不会使用新值更新 DOM,
        考虑使用track by 'the properties you expect to change' 只是要小心避免ngDupe 错误

        例如:

        <div ng-repeat="channel in UIModel.channels track by customExp(channel)">
        

        。 . .

        $scope.customExp = function(chan) {
            return chan.id+chan.thumbnail_url; // this has to ensure uniqueness
        }
        

        <div ng-repeat="channel in UIModel.channels track by channel.id+channel.thubnail_url">
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多