Ashok Poudel
Ashok Poudel

Reputation: 266

ng-repeat detect first occurrence of a condition

for the codes below, i want to detect first occurrence of this condition (msg.from_id==myid && msg.seen==1) and then ignore the rest items even the condition satisfies.

i tried ($first && msg.from_id==myid && msg.seen==1) but the condition may not always be applicable in the first index.

<table class="table table-striped table-hover">
    <tr ng-repeat="msg in messages"  >
        <td ng-class="{'orange': msg.from_id!=myid}" >

            <span class="seen" ng-show="msg.from_id==myid && msg.seen==1">
                   <i class="icon icon-ok border0 font12 green"></i> seen
            </span> 

            <b>{{msg.username}}</span> :</b>
            <span  ng-bind-html-unsafe="msg.message"></span>
        </td>
    </tr>
</table>

Actually what i want to achieve here is to show the "seen" span for the first occurring seen message (just like in Viber).

Upvotes: 3

Views: 828

Answers (1)

Michael
Michael

Reputation: 3326

EDIT: my fault, I changed the answer:

I created this example to provide you a possible solution; I changed the ngShow condition to ngIf and added a new condition !isDone. Once the first element is rendered, an ngInit will assign the isDone to true preventing further spans to be rendered

var app = angular.module("app", []);
app.controller("ctrl", function ($scope) {
    $scope.messages = [{
        from_id: 'test',
        seen: 1,
        username: 'username',
        message: 'message1'
    }, {
        from_id: 'test',
        seen: 0,
        username: 'username2',
        message: 'message2'
    }, {
        from_id: 'test2',
        seen: 1,
        username: 'username3',
        message: 'message3'
    }, {
        from_id: 'test2',
        seen: 1,
        username: 'username3',
        message: 'message3'
    }

    ];
    $scope.myid = "test";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<table ng-app="app" ng-controller="ctrl" class="table table-striped table-hover">
    <tr ng-repeat="msg in messages">
        <td ng-class="{'orange': msg.from_id!=myid}"> <span class="seen" ng-if="msg.from_id==myid && msg.seen==1 && !isDone">
                   <i ng-init="isDone=true" class="icon icon-ok border0 font12 green"></i> seen
            </span>  <b>{{msg.username}} :</b>
 <span ng-bind="msg.message"></span>

        </td>
    </tr>
</table>

Upvotes: 1

Related Questions