简体   繁体   中英

angular and socket.io - wrong code structure

I'm quite new with Node/Angular/.. and tried this simple script. But it doesn't work, whats wrong with it?

I always get Error: [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>

Without Angular it works fine, I guess there is an issue with the function scope? Thanks for help!

To make it work properly you should: 1) Add name to your ng-app:

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

2) Then you can define angular module and controller like this:

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

alternatively (it does the same):

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

PS. It doesn't matter, but name of you controller should be "rCtrl" rather than "rCtlr"

Here is a refference to angular docs: https://docs.angularjs.org/guide/controller

Update, thanks to MarkS: But .. see comment to Mark's answer

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

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