简体   繁体   中英

AngularJS ng-repeat hide repeat item if it is not an object

Here is my JSON data i am using in my repeat :

{
"2": {
    "id": 3,
    "0": {
        "avatar": "http:\\/\\/localhost\\/pottero\\/wp-content\\/plugins\\/dokan-live-chat\\/assets\\/images\\/avatar.png",
        "message": "Hello",
        "id": "2",
        "class": ""
    },
    "1": {
        "avatar": "http:\\/\\/localhost\\/pottero\\/wp-content\\/plugins\\/dokan-live-chat\\/assets\\/images\\/avatar.png",
        "message": "Hello Again",
        "id": "2",
        "class": ""
    }
  }
}

my html ng-repeat :

<div ng-repeat="message in $ctrl.messages" class="chat-messages" data-user_id="{{message.id}}" id="chat-messages-{{message.id}}">
  <div ng-repeat="msg in message" class="message {{msg.class}}">
    <img ng-src="{{msg.avatar}}" />
      <div class="bubble">
        '<div ng-bind-html="msg.message | trusted_html"></div>
        <div class="corner"></div>
      </div>
  </div>
</div>

what i want to do is when msg is not an object like "id" : 3 which is not an object so i don't want it in the repeat like ng-if msg is not object then don't include it in the repeating loop? i used ng-if="typeof(msg) !== 'object'" but it does hides all items. Please point me out how can i hide repeat item if its not an object

Convert each object to an array:

this.messages = Object.assign([], this.messages);
this.messages.forEach(msg => {
    msg = Object.assign([],msg));
});

When the ng-repeat directive iterates arrays, it only uses the properties that parse as integers.

For more information, see

use ng-container . You cannot use ng-repeat and ng-if on same element. Also, typeof is not a function it is an operator. Use ng-container if you do not to stamp extra html else you can additional div and add your ng-if condition on that element.

<div ng-repeat="message in $ctrl.messages" class="chat-messages" data-user_id="{{message.id}}" id="chat-messages-{{message.id}}">
  <div ng-repeat="msg in message" class="message {{msg.class}}">
    <ng-container ng-if="typeof msg !== 'object'"> --> Or you can add here `div` or other html element
      <img ng-src="{{msg.avatar}}" />
        <div class="bubble">
          '<div ng-bind-html="msg.message | trusted_html"></div>
          <div class="corner"></div>
        </div>
    </ng-container>
  </div>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM