Skip to content

Instantly share code, notes, and snippets.

@obengwilliam
Forked from jrthib/AnotherController.js
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save obengwilliam/70f23f491f0c961512d2 to your computer and use it in GitHub Desktop.
Save obengwilliam/70f23f491f0c961512d2 to your computer and use it in GitHub Desktop.
(function() {
'use strict';
function AnotherController($scope, socket) {
// use the socket factory through your app, but you must use socket.then
// so that the actions occur once the socket is established
socket.then(function(socket) {
socket.emit('some_socket_event', {});
});
$scope.buttonClicked = function() {
socket.then(function(socket) {
socket.emit('button_clicked_event', {});
});
};
}
AnotherController.$inject = [
'$rootScope',
'socket' // this is the SocketFactory which returns a promise
];
angular.module('controllers')
.controller('AnotherController', AnotherController);
})();
(function() {
'use strict';
function LoginController(LoginService) {
LoginService.login({
username: $username,
password: $password
}, function(user) {
if(user) {
// broadcast that there was a successful authentication
// to cause the socket to resolve.
$rootScope.$broadcast('authenticated');
} else {
// handle everything else
}
});
}
LoginController.$inject = [
'$rootScope',
'socket' // this is the SocketFactory which returns a promise
];
angular.module('controllers')
.controller('LoginController', LoginController);
})();
(function() {
'use strict';
function SocketFactory($q, $rootScope, socketFactory, $timeout, config) {
// create a promise instance
var socket = $q.defer();
// listen for the authenticated event emitted on the rootScope of
// the Angular app. Once the event is fired, create the socket and resolve
// the promise.
$rootScope.$on('authenticated', function() {
// resolve in another digest cycle
$timeout(function() {
// create the socket
var newSocket = (function() {
return socketFactory({
ioSocket: io.connect(config.API.SOCKET, {
query: config.API_HEADER + "=" + config.API_KEY
})
});
})();
// resolve the promise
socket.resolve(newSocket);
});
});
// return the promise
return socket.promise;
}
SocketFactory.$inject = [
'$q',
'$rootScope',
'socketFactory',
'$timeout',
'CONFIG'
];
angular.module('factories')
.factory('socket', SocketFactory);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment