1

I have a chat page where messages are displayed through ng-repeat on the array $scope.messages

I am subscribed to a backend-as-a-service and use their api for sending instant messages. When a message is received, the onChatMessage is executed.

What I'd like to do is to push any messages received to the the $scope.messages array so that the chat page displays the newly received message. However I don't know how to access the $scope.messages array from my function. Is this possible?

my controller:

.controller('ChatCtrl',function($scope,$stateParams,$ionicScrollDelegate,$q,principal){

 $scope.messages = ["test message 1","test message2];

})

This function calls when a message is received:

function onChatMessage(senderID,message){
     // senderID, message are predefined by the api of my backend-as-a-service
     // I'd like to push the message received here to scope.messages 
     // but accessing $scope here leads to undefined error. 
}
Terence Chow
  • 10,755
  • 24
  • 78
  • 141
  • possible duplicate of [Access Angular object's function from outside JS](http://stackoverflow.com/questions/14298361/access-angular-objects-function-from-outside-js) – ivarni Aug 20 '14 at 08:31

1 Answers1

2

yes.

function onChatMessage() {
    var scope = angular.element(...get the element...).scope()
    // example, angular.element(document.body).scope();
    scope.messages.push()
    ....
    scope.$digest() // updates the watched expressions
                    // - hence doing the angular's real-time view updates magic
}

That's one way.

sss
  • 1,259
  • 9
  • 23
  • `scope.messages.push()` really sould be wrapped in `$apply` – ivarni Aug 20 '14 at 08:30
  • use $apply() when you want to evaluate an expression. you can use $digest(). $apply() merely forces a $digest() – sss Aug 20 '14 at 08:31
  • true, but `(..).scope().$apply(function() { scope.messages.push() })` was what the docs recommended last time I looked. – ivarni Aug 20 '14 at 08:32
  • anyway you want. what $apply does is call a $digest after executing what needs to be applied. what really does the magic is $digest(). – sss Aug 20 '14 at 08:35
  • 1
    Yup, I just think you should edit one or the other into your answer which is why I commented. – ivarni Aug 20 '14 at 08:36
  • @Noypi Thanks! I'll loook into it now...Also, how would I call a factory from function? I have a factory named 'principal' which has some user information I'd like to use... – Terence Chow Aug 20 '14 at 08:37
  • Is it a directive factory or what factory? normally providers use this. from providers $get property – sss Aug 20 '14 at 08:39
  • i think you really wanted to configure your service. use providers. if you want to tweak existing services, use $decorators. – sss Aug 20 '14 at 08:41
  • @Noypi working like a charm. Thank you sir. I will look into providers and decorators – Terence Chow Aug 20 '14 at 08:44