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、内容和日期
根据你不想创建新 div 的问题,如果先前和当前 id 相等,则跳过循环。
所以一个简单的使用
并且可以直接在 html 上使用,所以
看看这个小提琴。
更新了小提琴,它检查任何现有的先前
数据绑定为你做的2种方式,如果你需要一些条件,创建一个新数组并循环通过它,改变视图,只需
1
2 3 4 5 6 7 8 |
<div ng–repeat="message in messages" ng–class="{‘sent’: userId == message.id, ‘received’: userId != 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"> |
试试这个:
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 |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/269136.html