从外部函数访问控制器中的变量(角度js)

时间:2014-08-20 08:25:23

标签: javascript angularjs

我有一个聊天页面,其中的消息通过数组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. 
}

1 个答案:

答案 0 :(得分:2)

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
}

这是单向的。

相关问题