我是angular.js的新手,并试图弄清楚如何将一个偶数处理程序中的json对象传递给控制器(或服务中的范围函数?)。我希望事件监听器在所有控制器之外等等,因为我喜欢仅在事件处理程序上使用的惯例来监听所有事件,而不是每个事件的几个事件监听器。我怎么能用Angular.js做到这一点?
客户代码:
var source = new EventSource('/subscribe');
source.addEventListener('open', function(e) {
console.log("connection was opened");
});
//Not using multi-listeners for each event.
source.addEventListener('message', function(e) {
var result = JSON.parse(e.data);
event = Object.keys(result)[0];
if (event == "cpuResult") {
//call the function of cpuScope
//pass json into it
} else if if (event == "networkResult") {
//call the function of neworkScope
and so on....
});
source.addEventListener('error', function(e) {
if (e.readyState == EventSource.CLOSED) {
}
},
假);
粗糙angular.js例子:
function cpuCtrl($scope) {
// the last received msg
$scope.msg = {};
var updateElement = function (msg) {
$scope.$apply(function () {
$scope.msg = JSON.parse(msg.data)
});
}
}