AngularJS Socket.io:无法读取未定义的属性'emit'

时间:2014-07-07 08:49:46

标签: javascript node.js angularjs socket.io

目前我正在尝试将angularjs与node和socketio一起使用。但是我收到以下错误。

  

TypeError:无法读取属性' emit'未定义的           at k。$ scope.EnteredUsername(http://localhost:1337/js/controllers.js:34:19

当调用enteredUsername() - Function时,似乎他不知道' socket'我的工厂有问题吗?

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 个答案:

答案 0 :(得分:1)

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

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