简体   繁体   中英

AngularJS Socket.io: Cannot read property 'emit' of undefined

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);
        }
    }]);

您错过了将其添加为字符串的情况:

.controller('usernameCtrl', ['$scope', 'socket', function($scope, socket) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM