" TypeError:无法读取属性' apply'未定义"

时间:2015-12-01 03:31:11

标签: javascript angularjs node.js express

使用node,express,socket.io,jade和angular。得到错误:TypeError: Cannot read property 'apply' of undefined。有什么建议吗?

index.js:

module.exports = function(app, res) {
  res.render('index', { title: 'Express' });
  var io = app.get('io');
  io.on('connection', function(socket){
  });
};

index.jade:

extends layout

block content

script.
    var app = angular.module('hackigur', []);
    var socket = io.connect();
    var refreshTimer = 10;

    app.controller('UpdateController', function($scope){
        //socket.on('update', function(msg){
            //$scope.refreshTimer = msg;
            //$scope.$apply();
        //});

        setInterval(secondTick,1000);

        function secondTick() {
            if(refreshTimer != 0) {
                refreshTimer -= 1;
            }
            $scope.refreshTimer = refreshTimer;
            $scope.$apply();
        };
    });

h1= title
p Welcome to #{title}

div(ng-controller="UpdateController")
    p(ng-bind="refreshTimer")

layout.jade:

doctype html
html(ng-app="hackigur")
  head
    title= title
    script(src = "/socket.io/socket.io.js")
    script(src = "/js/angular/angular.min.js")
  body
    block content

完整错误:

Server listening on port 3000
TypeError: Cannot read property 'apply' of undefined
    at Server.(anonymous function) [as on] (D:\Projects\hackigur\node_modules\so
cket.io\lib\index.js:364:15)
    at module.exports (D:\Projects\hackigur\server\api\index.js:30:8) at ...

1 个答案:

答案 0 :(得分:8)

router的{​​{1}}已在index.js中通过了app,因此:

module.export

我需要为module.export = function (app) { app.get( ... , function(..., res) { require(index.js)(app)(res); }; 外部app声明一个变量:

module.export

不完全理解为什么会有效,但似乎通过应用上述内容将正确的var x; module.export = function (app) { x = app; app.get( ... , function(..., res) { require(index.js)(x)(res); }; 对象传递给app