angular和socket.io - 错误的代码结构

时间:2014-11-21 13:10:46

标签: angularjs

我对Node / Angular / ..很新,并尝试了这个简单的脚本。但它不起作用,它有什么不对吗?

我总是收到错误:[ng:areq] http://errors.angularjs.org/1.3.0/ng/areq?p0=rCtlr&p1=not%20a%20function%2C%20got%20undefined

<!DOCTYPE html>
<html ng-app>
<head lang="en">
    <meta charset="UTF-8">
    <title>test</title>
    <script src="lib/angular/1.3.0/angular.min.js"></script>
    <script src="lib/socket.io/1.2.0/socket.io.js"></script>
</head>
<body ng-controller="rCtlr">
    <h1>{{xTime}}</h1>
    <script>
    function rCtlr($scope){
        var socket = io.connect();
        socket.on('updateTime', function (data) {
            $scope.xTime = data.updateTime;
            console.log(data);
        });
    }
    </script>
</body>
</html>

没有Angular它工作正常,我想功能范围有问题? 谢谢你的帮助!

2 个答案:

答案 0 :(得分:0)

为了使其正常工作,您应该: 1)为你的ng-app添加名称:

<html ng-app="myapp"> //myapp is an example name

2)然后你可以像这样定义角度模块和控制器:

angular.module("myapp",[]) // define module with name from ng-app
.controller('rCtlr',['$scope', function($scope){ //define controller for your module
    var socket = io.connect();
    socket.on('updateTime', function (data) {
        $scope.xTime = data.updateTime;
        console.log(data);
    });    
}]);

或(它也是如此):

var app = angular.module("myapp",[]);
app.controller('rCtlr',['$scope', function($scope){
      //controller body
}]);

PS。没关系,但你的控制器名称应该是“rCtrl”而不是“rCtlr”

以下是对角度文档的引用:https://docs.angularjs.org/guide/controller

答案 1 :(得分:0)

更新,感谢MarkS:但是......请参阅Mark的回答

<!DOCTYPE html>
<html >
<head lang="en">
    <meta charset="UTF-8">
<title>AngularSocket</title>
    <script src="lib/angular/1.3.0/angular.min.js" type="text/javascript"></script>
    <script src="lib/socket.io/1.2.0/socket.io.js" type="text/javascript"></script>
    <script src="app.js" type="text/javascript"></script>
</head>
<body data-ng-app="angApp">
    <div data-ng-controller="timeCtrl">
            <h1>{{xTime}}</h1>
    </div>
</body>
</html>

app.js:

angular
.module('angApp', [])
.controller('timeCtrl', ['$scope', function($scope) {
    var socket = io.connect();
    socket.on('updateTime', function (data) {
        $scope.xTime = data.updateTime;
        console.log(data);
    });
}]);