且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何根据条件在Angular JS中附加div(ANGULAR JS)

更新时间:2022-10-15 18:12:19

根据每个问题,如果以前的ID与当前的ID相等,则不想创建新的div. >

因此,简单地使用 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.id

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