How to append div in angular js depending upon condition (ANGULAR JS)
我有一个 div 重复我的消息数组中的所有值。如果下一个 message.id 等于上一个 message.id
,我无法弄清楚如何将下一个 message.content 附加到同一个 div(而不是创建新的)
我的代码的逻辑看起来像这样,但这不是真的。
1
2 3 4 5 6 7 8 9 |
<div ng–repeat=“message in messages” ng–class=“{‘sent’: userId ==
message.id, ‘received’: userId != message.id}”> //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 |
我的消息数组的结构包含 id、内容和日期
- 我不想将所有内容单独分组,我只想将它们与之前的 message.id 匹配
根据你不想创建新 div 的问题,如果先前和当前 id 相等,则跳过循环。
所以一个简单的使用 ng-if 可以解决你的问题。因为它创建了新的 DOM 元素,而不仅仅是显示或隐藏。喜欢:ng-if=”message.id !== messages[$index-1].id”,
并且可以直接在 html 上使用,所以 messages[-1].id 不会在 html 上崩溃。
看看这个小提琴。
更新了小提琴,它检查任何现有的先前 id 并在任何进一步的 id 匹配存在的情况下附加文本。
- 我不想跳过它,只想将当前处理的消息内容附加到先前创建的 div 如果它们的 id 相同
- @RichCuer:我创建了这个小提琴,它检查之前是否存在任何 id 直到 currentid till [n-1].id 并且如果 currentid 匹配到 [n+1].id 还附加文本。我也更新了答案。
- 是的,谢谢你是唯一得到我想要发生的事情的人,唯一的问题是我的 ID 不是整数,它们是像名字一样的字符串
数据绑定为你做的2种方式,如果你需要一些条件,创建一个新数组并循环通过它,改变视图,只需 push 到你的数组并且视图得到更新……如果你想要要检查 message.id 是否相等,只需使用 ng-show 来显示或隐藏,如下所示:
1
2 3 4 5 6 7 8 |
<div ng–repeat=“message in messages” ng–class=“{‘sent’: userId ==
message.id, ‘received’: userId != message.id}”>
|
- 这不是我正在寻找的答案:/
- 你能澄清你的问题吗?你的意思是你想要以前的message.id?让我们细化代码
- 如果 ng-repeat 当前处理的消息的 id 与上一个 message.id 相同,我只想将下一个 message.content 附加到上一个 div
- 我不想创建一个新的 div ;(
- 它不是 jQuery,只需更新您的模型,您的数据就会在视图中自动更新,让我为您更新我的答案
您可以使用 groupBy Angular 过滤器将您的数据分组到 message.id:
1
2 3 4 5 6 7 8 9 10 |
angular.module(‘app’, [‘angular.filter’])
.controller(‘MainController’, function($scope) { $scope.messages = [ {id: 1, date: ’01/12/1993′, content: ‘Hello’}, {id: 2, date: ’11/12/2017′, content: ‘Morning’}, {id: 1, date: ’05/08/2016′, content: ‘See you soon’}, {id: 2, date: ’22/01/1998′, content: ‘Bye’}, {id: 3, date: ’21/09/1932′, content: ‘Thanks’} ]; }); |
1
2 3 4 5 6 7 8 9 10 11 12 13 |
<script src=“https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js”>
<script src=“//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js”> |
- 我不想将所有内容单独分组,我只想在其消息 id 与上一个 message.id 匹配时对它们进行分组:(
试试这个:
Javascript
1
2 3 4 5 6 7 8 |
$scope.checkMessage = function($index) {
if($index > 0) { } |
HTML
1
2 3 4 5 6 7 |
// if ids are equal
// if ids are not equal |
你可以看看ng-if。
1
2 3 4 5 6 7 8 9 |
<div ng–repeat=“message in messages” ng–class=“{‘sent’: userId ==
message.id, ‘received’: userId != message.id}”> //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 |
- 不能解决任何问题,这涉及多个 ifs
- @RichCuer 也许你必须更具体,所有的回应都是平等的!
来源:https://www.codenong.com/44109178/