Now that the messages are sent out, let’s receive them. In order to do that, we need to subscribe to themessages-channelchannel and to react on the callback for when the message is sent and store it in the global messages array.

$scope.messages = [];

// Subscribing to the ‘messages-channel’ and triggering the message callback
Pubnub.subscribe({
    channel: $scope.channel,
    triggerEvents: ['callback']
});

// Listening to the callbacks
$scope.$on(Pubnub.getMessageEventNameFor($scope.channel), function (ngEvent, m) {
    $scope.$apply(function () {
        $scope.messages.push(m)
    });
});

// A function to display a nice uniq robot avatar 
$scope.avatarUrl = function(uuid){
    return 'http://robohash.org/'+uuid+'?set=set2&bgset=bg2&size=70x70';
};

Now we can display the messages by iterating over them. It will be displayed on the page each time a new message is sent.

<ul>
     <li ng-repeat="message in messages">
       <img src="{{avatarUrl(message.sender_uuid)}}" alt="{{message.sender_uuid}}">
       <span class="title">Anonymous robot #{{ message.sender_uuid }}</span>
       <p>{{ message.date | date:"MM/dd/yyyy 'at' h:mma"}}</br> {{ message.content }}</p>
     </li>
</ul>

At this point, you should be able to send and receive messages between clients in realtime.

results matching ""

    No results matching ""