Ng-Repeat 显示一次绑定的不规则行为

Ng-Repeat showing irregular behavior with one time binding

我在对象数组上有一个 运行 的 ng-repeat 指令。我面临一个特定的场景,当我用一次绑定绑定我的对象属性时,当我清除并将数据添加到我的对象数组中时,它们现在会被刷新,我是 运行 我的 ng-repeat。

这里要关注的一点是,所有这些功能以前都可以使用。

代码

<div class="search_result" data-ng-repeat="prod in searchResult track by $index" ng-show="ShowWhenResultPositive">
    <div class="media search-result-container">
        <div class="media-left">
            <div class="left ">&nbsp;</div>
            <div class="leftBottom">&nbsp;</div>
            <div class="rightTop">&nbsp;</div>
            <div class="rightBottom">&nbsp;</div>
            <div class="searchimg_container" ng-click="redirectionToPage(prod.url)">
                <!--<img src="{{prod.tkh_imageurl}}"  alt="Not Available" class="lazyload"/>-->
                <picture>
                    <source data-srcset="{{prod.desktopImage}}" media="(min-width: 768px)">
                    <source data-srcset="{{prod.mobileImage}}" media="(min-width: 320px)">
                    <img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" data-src="${properties.placeholderimage}" alt="Not Available" class="lazyload"><!--${properties.placeholderimage}-->
                </picture>
            </div>
        </div>
        <div class="media-body search-desc">
            <p ng-if="isPDF" class="subheading" ng-click="redirectionToPage(prod.url)">{{::prod.title}}</p>
            <p ng-if="!isPDF" class="subheading" ng-click="redirectionToPage(prod.url)">{{::prod.tkh_title}}</p>
            <p ng-if="!isPDF" class="resultdesc">{{::prod.tkh_description}}</p>
        </div>
    </div>
</div>

这是相同的代码。

来自文档:

Avoid using track by $index when the repeated template contains one-time bindings. In such cases, the nth DOM element will always be matched with the nth item of the array, so the bindings on that element will not be updated even when the corresponding item changes, essentially causing the view to get out-of-sync with the underlying data.

— AngularJS ng-repeat API Reference

如果您正在使用具有 唯一标识符 属性 的对象,您应该通过此标识符 而不是对象实例进行跟踪。如果您稍后重新加载数据,ngRepeat 将不必为它已经呈现的项目重建 DOM 元素,即使集合中的 JavaScript 对象已替换为新对象。对于大型集合,这会显着提高渲染性能。