AngularJS, Node.js & Socket.IO

2014-08-09 22:36:03

Every two seconds browser receives new post from server via socket.io, and everything happen without page refresh !

1. install angularjs and bootstrap via bower

bower install angularjs
bower install bootstrap

2. install node.js

3. install socket.io

npm install socket.io

4. SERVER: server.js

var http = require('http');
var socketio = require('socket.io');
var server = function (req, res) {
    return res.end('Node.js!');

var app = http.createServer(server);
var io = socketio.listen(app);

io.sockets.on('connection', function (socket) {
    setInterval(function () {
        var now = Date.now();
        var post = {id: now, name: 'Lorem Ipsum' + now};

        console.log('Emmitted', post);
        socket.emit('post', post);
    }, 2000);

console.log('Server running!');

To run the server use:

node server.js

5. CLIENT: app.js

angular.module('App', [])

    .controller('PostCtrl', function ($scope) {
        $scope.posts = [];

        var socket = io.connect('http://localhost:8080/');
        socket.on('post', function (post) {


5. CLIENT: index.html

<!DOCTYPE html>

<head lang='"en"'>
<meta charset="utf-8"/>
<title>AngularJS - Service</title>
<link href='"bower_components/bootstrap/dist/css/bootstrap.min.css"' rel='"stylesheet"'/>
<section 50px&quot;="" class='"container"' ng-app='"App"' style='"padding-top:'>
<section ng-controller='"PostCtrl"'>
<div class='"panel' panel-default&quot;="">
<div class='"panel-heading"'>Posts</div>
<div class='"panel-body"'>
<ul class='"list-group"'>
<li class='"list-group-item"' in="" ng-repeat='"post' orderby:'-id'&quot;="" posts="" |="">
                        #{{post.id}} / {{post.name}}
<script src='"lib/socket.io-1.0.6.js"'></script>
<script src='"bower_components/angularjs/angular.min.js"'></script>
<script src='"app.js"'></script>