[英]accessing a variable in controller from an outside function (angular js)
我有一個聊天頁面,其中通過ng-repeat
在$scope.messages
數組上顯示消息
我訂閱了后端即服務,並使用其api發送即時消息。 收到消息后,將執行onChatMessage
。
我想做的是將收到的所有消息推送到$scope.messages
數組,以便聊天頁面顯示新收到的消息。 但是我不知道如何從我的函數訪問$scope.messages
數組。 這可能嗎?
我的控制器:
.controller('ChatCtrl',function($scope,$stateParams,$ionicScrollDelegate,$q,principal){
$scope.messages = ["test message 1","test message2];
})
收到消息時調用此函數:
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.
}
是。
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
}
那是一種方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.