1

this is my main.js

var app = angular.module('app', []);

app.config(function ($routeProvider, $locationProvider) { 
   $locationProvider.html5Mode(true); // enable pushState
   $routeProvider.when('/', { 
      templateUrl: '/app.html',
      controller: 'AppCtrl'
   });
   $routeProvider.when('/another/route', { 
      templateUrl: '/deep.html',
      controller: 'AppCtrl'
   });
});
 var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
  socket.on('sendCustomer', function (data) {
    console.log(data);`
    //here i want to set controller scope 
  });
app.controller('AppCtrl', function ($scope) { 
    $scope.model = { 
       message: 'This is my app!!!' 
    };
    $scope.getCustomer = function(imageUrl) {
        alert("here i have to send command to socket io ");
        socket.emit('getCustomer', { });
    };

});

this is index.html

<!DOCTYPE html>
<html>
<head lang="en">
        <meta charset='utf-8'>
    <title>Egghead Videos</title>
    <link rel='stylesheet' href='/vendor/foundation/foundation.min.css'>
</head>
<body>

<div ng-app='app'>
   <ng-view></ng-view> 
</div>

<script type='text/javascript' src='/vendor/angularjs/angular.js'></script>
<script type='text/javascript' src='/socket.js'></script>
<script type='text/javascript' src='/main.js'></script>

</body>
</html>

this is the app.html

<h1>{{model.message}}</h1>

<a href="" ng-click="getCustomer()">Get Customer Data</a>

<!-- here i want to do ng-repeat of customer data -->

this is my server .js

var express = require('express');

var app = require('express')()
  , server = require('http').createServer(app)
  , io = require('socket.io').listen(server);
var fs = require('fs');
server.listen(8000);
app.use(express.static(__dirname));
app.use(app.router);

app.get('/', function (req, res) { 
  res.set('content-type', 'text/html');
  res.send(fs.readFileSync(__dirname + '/index.html', 'utf8'));
});
app.get('/another/route', function (req, res) { 
  res.set('content-type', 'text/html');
  res.send(fs.readFileSync(__dirname + '/index.html', 'utf8'));
});
io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
  socket.on('getCustomer', function (data) {
    console.log(data);
    socket.emit('sendCustomer', [{ name: 'c1' },{ name: 'c2' }]);
  });
});

so when sendCustomer event on client is fired in main.js , i want to show that data in controller throught ng-repeat , can i do that if yes then how ..

2 Answers 2

3

You should create a service like that to handle Socket.IO:

app.factory('socket', ['$rootScope', function ($rootScope) {
  var socket = io.connect();

  return {
    on: function (eventName, callback) {
      function wrapper() {
        var args = arguments;
        $rootScope.$apply(function () {
          callback.apply(socket, args);
        });
      }

      socket.on(eventName, wrapper);

      return function () {
        socket.removeListener(eventName, wrapper);
      };
    },

    emit: function (eventName, data, callback) {
      socket.emit(eventName, data, function () {
        var args = arguments;
        $rootScope.$apply(function () {
          if(callback) {
            callback.apply(socket, args);
          }
        });
      });
    }
  };
}]);

Then you can use it in your controller:

app.controller('AppCtrl', ['$scope', 'socket', function ($scope, socket) { 
    socket.on('sendCustomer', function (data) {
      $scope.customers.push(data);
    });
    $scope.model = { 
       message: 'This is my app!!!' 
    };
    $scope.customers = [];

    $scope.getCustomer = function(imageUrl) {
        alert("here i have to send command to socket io ");
        socket.emit('getCustomer', { });
    };
});

And finally in app.html:

<div ng-repeat="customer in customers">{{customer}}</div>

By the way, you could just use a REST API to do the same thing easily, but I'm guessing you want to try Socket.IO.

Sign up to request clarification or add additional context in comments.

1 Comment

quand j'utilise votre code, à partir du moment ou j'ajoute la partie "socket" dans le controller d'Angular. Cela détruit le rendu de la page. Est-ce que vous auriez une idée de ce qui cause cela? Et ou de comment trouver ce qui cloche?
2

First off, if you're going to use anything within a module, you have to pass it in.

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

Because you're doing stuff in socket, outside of Angular, you'll also have to pay attention to $apply() to get these changes to appear inside of Angular.

I could type out more on this, but really, Brian Ford's socket.io seed and related blog post are the best starting points for sockets + express + angular.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.