[英]AngularJS pass callback from controller to service
I have a controller defined as follows: 我有一个控制器定义如下:
menuController.controller('menuController', ['$scope', '$rootScope', '$log', 'techMessageService', 'subscriptionService',
function ($scope, $rootScope, $log, techMessageService, subscriptionService) {
$scope.newTechMessage = false;
var handleNewTechMessage = function (data) {
$log.log('handleTechMessage: ' + data);
$scope.newTechMessage = true;
};
var init = function () {
$log.log('menuController init');
subscriptionService.subscribeTechMessages(handleNewTechMessage);
};
init();
}]);
subscriptionService is like: subscriptionService就像:
subscriptionService.service('subscriptionService', ['$log', 'backendService', function ($log, backendService) {
this.subscribeTechMessages = function (handler) {
$log.log('subscriptionService:subscribeTechMessages');
var socket = io.connect('https://localhost:9001');
socket.on('connect', function () {
socket.emit('adduser', '80040002');
});
backendService.post('/subscribeTechMessages');
socket.on('NEW_MESSAGE', handler);
};
this.unsubscribeTechMessages = function () {
$log.log('subscriptionService:unsubscribeTechMessages');
return backendService.post('/unsubscribeTechMessages');
};
}]);
The problem I have is the handleNewTechMessage function which is passed to the service. 我遇到的问题是传递给服务的handleNewTechMessage函数。 It is executed as an event handler, it sets newTechMessage scope variable to true but the change is not reflected on the view.
它作为事件处理程序执行,它将newTechMessage范围变量设置为true,但更改不会反映在视图上。 I have newTechMessage bind on the view and it is still false.
我在视图上有newTechMessage绑定,它仍然是假的。 What do I misunderstand?
我有什么误解? I suppose it should work but I wonder if that function passing is all right when modifying scope variables.
我想它应该工作,但我想知道在修改范围变量时,函数传递是否正常。
Call digestion 叫消化
In the handleNewTechMessage
callback, call a scope digestion with $scope.$apply()
. 在
handleNewTechMessage
回调中,使用$scope.$apply()
调用范围消化。 Without this digestion call, there is no reason Angular should understand something may have changed. 如果没有这种消化调用,Angular就没有理由理解可能已经改变的东西。
Callbacks as an array 回调为数组
In your implementation, each handler registration makes a call to io.connect
. 在您的实现中,每个处理程序注册都会调用
io.connect
。 Better have an internal array the callbacks are pushed in, and looped in on socket message. 最好有一个内部数组,回调被推入,并在socket消息中循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.