簡體   English   中英

從外部函數(角度js)訪問控制器中的變量

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM