问题
To preface, I have an Ionic app connected to a Node server via a websocket and the Node server is connected to a C++ app via a TCP socket. I have this service that connects and serves up the socket but also watches for a nack
response so that it can issue an alert notifying the user of the error:
(function(){
'use strict';
angular.module('tacoCorp.services')
.factory('Socket', Socket);
Socket.$inject = ['socketFactory', 'OSDP', '$rootScope'];
function Socket(socketFactory, OSDP, $rootScope) {
var socket = io('localhost:3000');
socket = socketFactory({ioSocket: socket});
socket.on('connect', function() {
console.log('connected');
});
socket.on('nack', function(data) {
console.log(data);
var error = OSDP.parse(data);
$rootScope.$broadcast('nack', error);
});
return socket;
}
}());
I have this in each controller listening so that it can issue the popup:
$scope.$on('nack', function(e, err) {
console.log(err);
var alertPopup = $ionicPopup.alert({
title: 'Error',
template: err.error
});
});
My problem is that it is firing multiple times even though my there is only one controller for each state/view. Almost as if $destroy
isn't happening or it's not removing the listener. Still happens if I do this:
var nackListener = $scope.$on('nack', function(e, err) {
console.log(e);
var alertPopup = $ionicPopup.alert({
title: 'Error',
template: err.error
});
});
$scope.$on('$destroy', nackListener);
I'm not sure what the best way to handle this is.
回答1:
As Radim Köhler pointed out $ionicConfigProvider.views.maxCache(0)
fixes this issue where cache:false
on the state does not. You could also do this:
$scope.$on("$ionicView.afterLeave", function () {
$ionicHistory.clearCache();
});
Best way for me is to just pick one controller to put it on and be done with it.
来源:https://stackoverflow.com/questions/35076821/broadcast-to-current-scope