我的问题是,如果不引用 $rootScope 中的消息,我无法弄清楚如何从通道 api 接收消息。这是该服务的一个片段:
myapp.factory('myService', function($http, $rootScope){
var that = this;
var result;
var onOpened = function(){
console.log("It opened");
}
onMessage = function(message){
$rootScope.myMessage = JSON.parse(message.data); // this works
$rootScope.$apply(); // but I don't wanna use it
}
var channel = new goog.appengine.Channel('{{ token }}'); // yes, I'm mixing frameworks, relax...
var socket = channel.open();
socket.onopen = onOpened;
socket.onmessage = onMessage;
// I should be returning the onMessage result here, and somehow watching it
})
我不知道如何在不调用 rootscope 的情况下将 onMessage 函数的结果返回给控制器。
控制器很简单:
myapp.controller('cntrl1', function($scope, $rootScope, myService){
// It seems that a watch would work but I can't figure out how to
// get the 'return' of the service wired to allow this method to be successful.
// Remember, the onMessage is a json message sent from another client through the
// server.
$scope.message = $rootScope.myMessage // not necessary
$scope.$watch('myService.parsed', function(newVal, oldVal, scope){
if(newVal){
console.log("changed");
scope.message = newVal.data;
} else {
console.log(oldVal);
scope.message = oldVal;
}
})
})
我知道每次全局命名空间被污染时,一只小狗就会死去,但在这种情况下,我可能不得不牺牲一只小狗。我被困住了。