Manish Kumar
Manish Kumar

Reputation: 10482

$scope array not getting updated

Inside a controller I have this code:

$rootScope.$on('chat_contact', function(event, data) {          
            var message = data.message;
            if(data.key === 'IM_MSG') {
                console.log("chat_contact.........");
                var contact = $scope.contacts[message.sndrId];
                if(contact) {
                    contact.lastMsg = message.text;
                    contact.sndrName = message.sndrName;
                } else {
                    $scope.contacts[7] = {
                        'lastMsg': message.text,
                        'sndrName': message.sndrName 
                    }
                }
            }
        });

Here is my html code:

    <li class="item item-avatar item-icon-left1 item-icon-right" ng-repeat="(id, contact) in contacts" ui-sref="app.chat-single" on-hold="moreOptions('{{id}}')">
      <img src="venkman.jpg">
      <h2>{{contact.sndrName}}</h2>
      <p><span class='margin-l-10'>{{contact.lastMsg}}</span></p>

Problem is

$scope.contacts[7] = {
  'lastMsg': message.text,
  'sndrName': message.sndrName 
}

is adding a new enter to contacts but its not getting render in html

Upvotes: 1

Views: 69

Answers (2)

Jenson Raby
Jenson Raby

Reputation: 789

use $scope.$apply(); after the loop execution

$rootScope.$on('chat_contact', function(event, data) {          
        var message = data.message;
        if(data.key === 'IM_MSG') {
            console.log("chat_contact.........");
            var contact = $scope.contacts[message.sndrId];
            if(contact) {
                contact.lastMsg = message.text;
                contact.sndrName = message.sndrName;
            } else {
                $scope.contacts[7] = {
                    'lastMsg': message.text,
                    'sndrName': message.sndrName 
                }
            $scope.$apply();
            }
        }
    });

Upvotes: 1

Akash Agrawal
Akash Agrawal

Reputation: 2299

Can you try adding $apply() ?

I was facing the same problem and it resolved mine.

$scope.$apply(function(){
    $scope.contacts[7] = {
    'lastMsg': message.text,
    'sndrName': message.sndrName 
    }
});

I'm not sure if it's correct but you can give it a try.

Upvotes: 2

Related Questions