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. } 
1

1 Answer 1

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.

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

9 Comments

scope.messages.push() really sould be wrapped in $apply
use $apply() when you want to evaluate an expression. you can use $digest(). $apply() merely forces a $digest()
true, but (..).scope().$apply(function() { scope.messages.push() }) was what the docs recommended last time I looked.
anyway you want. what $apply does is call a $digest after executing what needs to be applied. what really does the magic is $digest().
Yup, I just think you should edit one or the other into your answer which is why I commented.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.