0

currently I am trying to use angularjs with node and socketio. But I am getting the following error.

TypeError: Cannot read property 'emit' of undefined at k.$scope.EnteredUsername (http://localhost:1337/js/controllers.js:34:19)

It seems like he doesnt know 'socket', when the enteredUsername()-Function is called. Is there something wrong with my factory?

app.js:

'use strict';

angular.module('myApp', [
  'ngRoute',
  'myApp.filters',
  'myApp.services',
  'myApp.directives',
  'myApp.controllers'
])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/viewUsername', {templateUrl: 'partials/username.html', controller: 'usernameCtrl'});
  $routeProvider.when('/viewImpressum', {templateUrl: 'partials/impressum.html', controller: 'impressumCtrl'});
  $routeProvider.otherwise({redirectTo: '/viewUsername'});
}]);

controllers.js:

'use strict';

/* Controllers */

angular.module('myApp.controllers', [])
    .factory('socket', function($rootScope) {
        var socket = io.connect('http://localhost:1337');
        return {
            on: function(eventName, callback) {
                socket.on(eventName, function() {
                    var args = arguments;
                    $rootScope.$apply(function() {
                        callback.apply(socket, args);
                    });
                });
            },
            emit: function(eventName, data, callback) {
                socket.emit(eventName, data, function() {
                    var args = arguments;
                    $rootScope.$apply(function() {
                        if(callback) {
                            callback.apply(socket, args);
                        }
                    });
                });
            }
        };
    })
    .controller('usernameCtrl', ['$scope', function($scope, socket) {
        $scope.username = 'guest';

        $scope.EnteredUsername = function() {
            var username = $scope.username;
            socket.emit('enteredUsername', username);
        }
    }]);

1 Answer 1

1

You missed adding it as string:

.controller('usernameCtrl', ['$scope', 'socket', function($scope, socket) {
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.