1

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

2
  • Where are you adding?\ Commented Aug 23, 2016 at 2:30
  • inside a controller Commented Aug 23, 2016 at 4:49

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

But why its happening like that simply adding to $scope should update the data
@manish usually if you change data inside an event you need to $apply()
adding to what @gyc stated, $apply evaluates an expression and triggers a digest cycle, making Angular execute all registered watch listeners and update any view bindings.
@gyc we can add any data to $scope under a click to other event correct & it generally reflect the changes
@manish yes, the ngClick directive includes $apply() in source code
|
1

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();
            }
        }
    });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.