Controller wont update DOM on async callback

272 views
Skip to first unread message

Žiga Vidic

unread,
May 26, 2012, 6:58:40 AM5/26/12
to ang...@googlegroups.com
Hi everyone. I'm a total newbie, but I could not find any answer regarding this or similar problem. My problem is, that, I can easily update messages array when working by example from angular.js website, but If I try to update this array with asynchronous callback from PubNub, I will see changes only in browser console and not in DOM. Problem is on PubNub callback. How should I do that correctly?

Thank you!

Here is my code:

html:
<div class="ui-grid-a" ng-controller="ChatController">
<div class="ui-block-a" id="incomingMessages">
<div class="message" ng-repeat="message in messages">
<span class="time">{{ message.time | date:'hh:mm'}}</span>
<span class="username">{{message.username}} </span>
{{message.text}}
</div>
</div>
<div class="ui-block-a" id="form">
<div data-role="fieldcontain">
<form ng-submit="addMessage()" data-ajax="false">
<input ng-model="yourMessageText" id="messageText"
  placeholder="Write your message" />
</form>
</div>
</div>
</div>

js:
function ChatController($scope) {
    $scope.messages = [{text: 'test1', username: 'un', time: new Date()}]; // are assembled from text and username and time
    // this one gets updated in browser
    $scope.messages.push({text: 'test2', username: 'un', time: new Date()});

    $scope.subscribeToChatChannel = function(uuid) {
        pubnub.subscribe({
            channel  : uuid,
            callback : function(message) {
                //appendMessageToDom(message);
                //setChatBuddy(message.uuid, message.un);

                // this one doesn't update in browser, but if I inspect $scope.messages in browser console,
                // message is pushed into array
                $scope.messages.push(message);
                console.log(message);
            },
            connect  : function() {
                console.log("CHAT CONNECTION ESTABLISHED.");
            },
            error    : function(e) {
                console.log(e);
            }
        });
    }
    $scope.subscribeToChatChannel('fakeUuid');

    // working fine
    $scope.addMessage = function() {
        var myUsername = localStorage.getItem('username');
        $scope.messages.push({
            text: $scope.yourMessageText,
            username: myUsername,
            time: new Date()
        });

        $scope.yourMessageText = '';
        //sendMessageToChaBuddy(chatBuddy.uuid);
        sendMessageToChaBuddy('fakeUuid');  // check this fakeUuid as channel in pubnub console ;)
    };
}

Žiga Vidic

unread,
May 26, 2012, 8:40:12 AM5/26/12
to ang...@googlegroups.com
This should help me:  https://groups.google.com/forum/?fromgroups#!topic/angular/J746gJvdVnc 
Sorry, I didn't try to search for pubnub related to angular.
Reply all
Reply to author
Forward
0 new messages