簡體   English   中英

角度ng重復導致閃爍

[英]Angular ng-repeat causes flickering

我正在使用以下代碼顯示縮略圖列表:

<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的過程中雙重緩沖區或沒有刪除列表?

與@ cexbrayat的答案一致,如果你沒有任何ID,你也可以將它關聯起來並track by $index 這是ng-repeat期間的內部迭代#。

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

您可以使用唯一標識符在ng-repeat使用track by 如果我認為你的頻道對象有一個id,你可以這樣做:

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

跟蹤避免了每次更新時完整的DOM刪除和重新創建,因為Angular將能夠跟蹤元素是否與先前相同並將保留DOM元素。

首先嘗試@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);禁用代碼中元素的動畫$animate.enabled('div.channel', false);

我有同樣的問題,使用$ index的軌道終於解決了我的問題。 起初我沒想到它,因為我直接在圖像標簽中使用了另一個ng-repeat。 一旦我把它放在父級div(以及)ng-repeat上就可以了:

<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 -->

作為一個說明:

如果使用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">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM