因此,简单地使用 ng-if 可以解决您的问题,因为它创建了新的DOM元素,而不仅仅是显示或隐藏.就像: ng-if ="message.id!== messages [$ index-1] .id" ,它可以直接在html上使用,因此 messages [-1] .id 不会在html上崩溃.请参见小提琴.更新了> 小提琴 ,它会检查是否存在任何以前的 id并附加文本(如果还有其他 id 匹配存在的文本).I have a div that repeats all of the values in my messages array. I'm having trouble figuring out how to append the next message.content to the same div (not to create new one) if the next message.id is equal to the previous message.idMy code's logic look like this but this isn't really it. <div ng-repeat="message in messages" ng-class="{'sent': userId == message.id, 'received': userId != message.id}"> <div class="message"> //message.content goes here //I dont want to create a new div if the next message.id is equal to the previous message.id //Planning to just append the content here //If its not equal then repeat the div as usual //Please help T_T </div> </div>The structure of my messages array contains id, content, and date 解决方案 As per question you don't want to create new div just skip the loop if previous and current ids are equal.So a simple use of ng-if can solve your problem., because it create new DOM element rather than just showing or hiding. Like : ng-if="message.id !== messages[$index-1].id",and it can be used directly on html so messages[-1].id won't crash on html.See this Fiddle.Updated fiddle, which check for any existing previous id and append text if any further id matches existence one. 这篇关于如何根据条件在Angular JS中附加div(ANGULAR JS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!