如何根据条件在Angular JS中附加div(ANGULAR JS) [英] How to append div in angular js depending upon condition (ANGULAR JS)

查看:53
本文介绍了如何根据条件在Angular JS中附加div(ANGULAR JS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div,它重复了我的message数组中的所有值.如果下一个message.id等于上一个message.id,我很难弄清楚如何将下一个message.content附加到同一个div(而不是创建新的div).

我的代码的逻辑看起来像这样,但这不是真的.

 < div ng-repeat =邮件中的邮件" ng-class ="{'sent':userId ==message.id,已接收":userId!= message.id}>< div class ="message">//message.content在这里//如果下一个,我不想创建一个新的divmessage.id等于上一个message.id//计划只在此处附加内容//如果不相等,则照常重复div//请帮助T_T</div></div> 

我的邮件数组的结构包含id,内容和日期

解决方案

根据每个问题,如果以前的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.

这篇关于如何根据条件在Angular JS中附加div(ANGULAR JS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆