我大约3周前开始使用AngularJS,并开始编写一个简单的应用程序,它从外部库(OnReceiveMessage)获取异步数据,然后(使用Angular)编辑范围,以显示和执行其他信息,甚至回复此邮件。 首先,我开始将对象声明为应用程序控制器,并且它可以工作,但它是一团糟,这不是正确的事情。 我的问题是:如何启动这个异步客户端(通过Web套接字通信)并将此库的外部函数(发送和异步接收)传递给Angular,以便用它做任务(范围,回复等...)
external.js
Example:
var client = new ExtClient({params}); //not setting callbacks
Client.onMessageArrived = myCallbackHandler;
var message = new ExtMessage("Hi there");
Client.send(message);
function myCallbackHandler(message) {
console.log("onMessageArrived");
}
app.js
var app = angular.module('myApp', ['connectionService']);
app.controller('MainController', [ '$scope',
function($scope) {
//I want to catch the myCallbackHandler function async with the message
//and use the client.send(message) with the response...
$scope.messageTable.push({message.id, message.value}); //messageTable is bind in the view to create a table
}]);
答案 0 :(得分:1)
这是您要创建服务的情况。
angular.module('myApp', ['connectionService'])
.factory('messageService', function() {
var client = new ExtClient({
// set your params
});
return {
listen: function(event, callback) {
/* code to register a callback on an event */
client[event] = callback;
},
push: function(id, value) {
/* code to push a message */
client.send(new ExtMessage(message));
}
};
})
.controller('MainController', ['messageService' function(messageService) {
messageService.listen('onMessageArrived', function(message) {
console.log("onMessageArrived");
});
messageService.push('some id', 'some message');
}]);
答案 1 :(得分:1)
您还可以在$ scope或$ rootScope上使用$ broadcast(),$ emit()和$ on()来考虑应用程序的不同元素之间的通信。更多:
https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope
http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/