• Stars
    star
    1,520
  • Rank 30,164 (Top 0.7 %)
  • Language
    JavaScript
  • Created over 11 years ago
  • Updated about 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Socket.IO component for AngularJS

angular-socket-io Build Status

Bower Component for using AngularJS with Socket.IO, based on this.

Install

  1. bower install angular-socket-io or download the zip.
  2. Make sure the Socket.IO client lib is loaded. It's often served at /socket.io/socket.io.js.
  3. Include the socket.js script provided by this component into your app.
  4. Add btford.socket-io as a module dependency to your app.

Usage

This module exposes a socketFactory, which is an API for instantiating sockets that are integrated with Angular's digest cycle.

Making a Socket Instance

// in the top-level module of the app
angular.module('myApp', [
  'btford.socket-io',
  'myApp.MyCtrl'
]).
factory('mySocket', function (socketFactory) {
  return socketFactory();
});

With that, you can inject your mySocket service into controllers and other serivices within your application!

Using Your Socket Instance

Building on the example above:

// in the top-level module of the app
angular.module('myApp', [
  'btford.socket-io',
  'myApp.MyCtrl'
]).
factory('mySocket', function (socketFactory) {
  return socketFactory();
}).
controller('MyCtrl', function (mySocket) {
  // ...
});

API

For the most part, this component works exactly like you would expect. The only API addition is socket.forward, which makes it easier to add/remove listeners in a way that works with AngularJS's scope.

socket.on / socket.addListener

Takes an event name and callback. Works just like the method of the same name from Socket.IO.

socket.removeListener

Takes an event name and callback. Works just like the method of the same name from Socket.IO.

socket.removeAllListeners

Takes an event name. Works just like the method of the same name from Socket.IO.

socket.emit

Sends a message to the server. Optionally takes a callback.

Works just like the method of the same name from Socket.IO.

socket.forward

socket.forward allows you to forward the events received by Socket.IO's socket to AngularJS's event system. You can then listen to the event with $scope.$on. By default, socket-forwarded events are namespaced with socket:.

The first argument is a string or array of strings listing the event names to be forwarded. The second argument is optional, and is the scope on which the events are to be broadcast. If an argument is not provided, it defaults to $rootScope. As a reminder, broadcasted events are propagated down to descendant scopes.

Examples

An easy way to make socket error events available across your app:

// in the top-level module of the app
angular.module('myApp', [
  'btford.socket-io',
  'myApp.MyCtrl'
]).
factory('mySocket', function (socketFactory) {
  var mySocket = socketFactory();
  mySocket.forward('error');
  return mySocket;
});

// in one of your controllers
angular.module('myApp.MyCtrl', []).
  controller('MyCtrl', function ($scope) {
    $scope.$on('socket:error', function (ev, data) {

    });
  });

Avoid duplicating event handlers when a user navigates back and forth between routes:

angular.module('myMod', ['btford.socket-io']).
  controller('MyCtrl', function ($scope, socket) {
    socket.forward('someEvent', $scope);
    $scope.$on('socket:someEvent', function (ev, data) {
      $scope.theData = data;
    });
  });

socketFactory({ ioSocket: }}

This option allows you to provide the socket service with a Socket.IO socket object to be used internally. This is useful if you want to connect on a different path, or need to hold a reference to the Socket.IO socket object for use elsewhere.

angular.module('myApp', [
  'btford.socket-io'
]).
factory('mySocket', function (socketFactory) {
  var myIoSocket = io.connect('/some/path');

  mySocket = socketFactory({
    ioSocket: myIoSocket
  });

  return mySocket;
});

socketFactory({ scope: })

This option allows you to set the scope on which $broadcast is forwarded to when using the forward method. It defaults to $rootScope.

socketFactory({ prefix: })

The default prefix is socket:.

Example

To remove the prefix:

angular.module('myApp', [
  'btford.socket-io'
]).
config(function (socketFactoryProvider) {
  socketFactoryProvider.prefix('');
});

Migrating from 0.2 to 0.3

angular-socket-io version 0.3 changes X to make fewer assumptions about the lifecycle of the socket. Previously, the assumption was that your application has a single socket created at config time. While this holds for most apps I've seen, there's no reason you shouldn't be able to lazily create sockets, or have multiple connections.

In 0.2, angular-socket-io exposed a socket service. In 0.3, it instead exposes a socketFactory service which returns socket instances. Thus, getting the old API is as simple as making your own socket service with socketFactory. The examples below demonstrate how to do this.

Simple Example

In most cases, adding the following to your app should suffice:

// ...
factory('socket', function (socketFactory) {
  return socketFactory();
});
// ...

Example with Configuration

Before:

angular.module('myApp', [
  'btford.socket-io'
]).
config(function (socketFactoryProvider) {
  socketFactoryProvider.prefix('foo~');
  socketFactoryProvider.ioSocket(io.connect('/some/path'));
}).
controller('MyCtrl', function (socket) {
  socket.on('foo~bar', function () {
    $scope.bar = true;
  });
});

After:

angular.module('myApp', [
  'btford.socket-io'
]).
factory('socket', function (socketFactory) {
  return socketFactory({
    prefix: 'foo~',
    ioSocket: io.connect('/some/path')
  });
}).
controller('MyCtrl', function (socket) {
  socket.on('foo~bar', function () {
    $scope.bar = true;
  });
});

FAQ

Closed issues labelled FAQ might have the answer to your question.

See Also

License

MIT

More Repositories

1

write-good

Naive linter for English prose
JavaScript
4,898
star
2

angular-express-seed

A great starting point for writing AngularJS apps backed by an Express-powered node.js server.
JavaScript
1,517
star
3

ngmin

**deprecated** AngularJS Pre-minifier –> use ng-annotate –>
JavaScript
860
star
4

angular-socket-io-seed

A great starting point for writing AngularJS apps backed by a Socket.io-powered node.js server.
JavaScript
771
star
5

angular-express-blog

Example AngularJS app using an Express + Node.js backend.
JavaScript
600
star
6

angular-markdown-directive

AngularJS markdown directive using Showdown.js
JavaScript
568
star
7

angular-socket-io-im

Simple Instant Messaging app using AngularJS + Socket.IO
JavaScript
395
star
8

grunt-conventional-changelog

Grunt task for generating a changelog from git metadata
JavaScript
243
star
9

angular-modal

Simple AngularJS service for creating modals
JavaScript
233
star
10

angular-dragon-drop

Drag and Drop for AngularJS
JavaScript
225
star
11

grunt-ngmin

Grunt task for ngmin
JavaScript
170
star
12

angular-d3-demo

JavaScript
148
star
13

participating-in-open-source

141
star
14

mary-poppins

Keeps your GitHub PRs and issues tidy
JavaScript
123
star
15

briantford.com

sup
CSS
99
star
16

angular-phonegap-ready

JavaScript
95
star
17

brian-talks-about-angular-with-lots-of-data

Lightning talk about making Angular apps that deal with lots of data fast
89
star
18

adj-noun

Gives you a random adj-noun pair that you can use as a unique identifier
JavaScript
66
star
19

react-palm

Work in progress, docs forthcoming i promise
JavaScript
59
star
20

grunt-google-cdn

JavaScript
59
star
21

where-does-this-run

dynamic analysis tool to determine what environments arbitrary JavaScript will run in
JavaScript
51
star
22

angular-phonegap-notification

JavaScript
51
star
23

astral

AST tooling framework for JavaScript
JavaScript
47
star
24

angular-phonegap-geolocation

JavaScript
40
star
25

angular-unicorn-directive

Add a <unicorn></unicorn> to your app!
JavaScript
37
star
26

angular-phonegap-accelerometer

JavaScript
33
star
27

socialize

Use twitter as a key-value database
JavaScript
31
star
28

allthethings

ASCII Art
Shell
23
star
29

phone-kitten

WIP: angular "phonecat" tutorial redone with "The New Angular Routerâ„¢"
JavaScript
23
star
30

007

Returns a deep copy of an object with all functions converted to spies.
JavaScript
21
star
31

metahub

github metadata cache/mirror
JavaScript
20
star
32

kawaii

node module for determining if the contents of a string are cute
JavaScript
17
star
33

eshighlight

highlight javascript code based on an esprima AST
JavaScript
16
star
34

brian-talks-about-decorators

Lightning talk about AngularJS decorators
16
star
35

weasel-words

for detecting weasel words
JavaScript
15
star
36

alfred-cool-ascii-faces

15
star
37

passive-voice

for detecting passive voice
JavaScript
15
star
38

grunt-ddescribe-iit

Grunt task for checking that iit and ddescribe don't make it into committed code
JavaScript
14
star
39

grunt-merge-conflict

Grunt plugin for preventing you from accidentally comitting a merge conflict into your project
JavaScript
14
star
40

philosobot

Philosophical IRC bot powered by Node.js
JavaScript
12
star
41

qequire

Promisify modules as you require them.
JavaScript
12
star
42

quinoa

static site generator with versioning
JavaScript
12
star
43

socketron

An event-driven state machine for routing sockets.
JavaScript
12
star
44

poppins-pr-checklist

JavaScript
11
star
45

url-resolver.js

JavaScript
9
star
46

hitch-a-ride

Mobile app for EECS 441
9
star
47

pierogi

tasty alternative CLI for npm focused on discoverability
JavaScript
8
star
48

angular-yeoman-shopping

JavaScript
8
star
49

brian-talks-about-animations

For Devoxx 2013
CSS
8
star
50

angular-shopping-demo

JavaScript
7
star
51

hitch-a-ride-client

Web-based client, shared by hitch-a-ride webapp and Phonegap-powered Android app
JavaScript
7
star
52

sublime-text-javascript

My personal Sublime Text 3 JavaScript Package
Shell
7
star
53

meatmail

JavaScript
7
star
54

astral-angular-annotate

AngularJS DI annotation pass for astral
JavaScript
6
star
55

angular-enabled

complement to angular-disabled
JavaScript
6
star
56

socialjam

A collaborative music composition application created with the HTML5 canvas during Facebook Camp Hackathon. Demo available on Facebook. Server not included.
PHP
6
star
57

readme-good

naive judge of the quality of a markdown readme for an open source project
JavaScript
5
star
58

dmc13-slides

My slides for DMC13 - http://www.mobileconference.nl/
JavaScript
5
star
59

angular-futuristic-router

WIP
JavaScript
5
star
60

btford-env

my environment (settings, dotfiles, etc)
Emacs Lisp
5
star
61

poppins-check-cla

plugin for poppins-pr-checklist
JavaScript
4
star
62

poppins-prioritize

Mary Poppins plugin for prioritizing issues based on labels
JavaScript
4
star
63

angular-animate-shim

adds a `$animate` service for versions of Angular `1.1.x` and below
JavaScript
4
star
64

meatgame

JavaScript
4
star
65

router-examples

WIP code/docs on routing in AngularJS 2.0
4
star
66

astral-pass

JavaScript
4
star
67

angular-contact-manager

JavaScript
3
star
68

wrapgeni.us

CSS
3
star
69

insertify

dumb string insertion util for node.js
JavaScript
3
star
70

fn-params

return the names of a function's parameters
JavaScript
3
star
71

poppins-check-commit

JavaScript
3
star
72

clicli

makes literally any node module into a CLI tool
3
star
73

style-guide

my personal code style guide for all programming and natural languages
3
star
74

ideas

Collection of ideas for open source projects.
3
star
75

poppins-exec

mary-poppins plugin for running local commands in response to GitHub comments
JavaScript
2
star
76

j4y35

/\/\43k |_|R j4y35 /\/\04R 1337 d00d
JavaScript
2
star
77

github-prune-issues

CLI for closing old Github issues
JavaScript
2
star
78

npm-nginx-cache

nginx configs
Shell
2
star
79

fn-body

given a function, get its body as a string
JavaScript
2
star
80

brian-talks-about-karma

JavaScript
2
star
81

poppins-mock

mocks for mary-poppins
JavaScript
2
star
82

webrebels2013

JavaScript
2
star
83

angular-simplify-module

minification tool to combine `angular.module`s
JavaScript
2
star
84

property-lolscriptors

patches property descriptors so you can configure "non-configurable" properties of objects
JavaScript
2
star
85

poppins-label

JavaScript
2
star
86

google-music-shortcuts

Applescripts that can be bound to keys via Automator services to give Google Music global hotkeys in OS X
2
star
87

jsGameLib

JavaScript game library
JavaScript
2
star
88

multiple.singles

totally serious distributed dating site
CSS
2
star
89

sweet-observe

Poor man's object.observe to get object diffs with Sweet.js
JavaScript
2
star
90

ngmin-dynamic

JavaScript
1
star
91

intermediately-sized-hadron-collider

a tool for testing metaprogramming witchcraft
JavaScript
1
star
92

hitch-a-ride-android

Hitch-a-ride android app
JavaScript
1
star
93

brian-talks-about-angulars-compiler

TODO
1
star
94

end-runner

HTML5 Game for 2013 Wolverinesoft 48-Hour Hackathon
JavaScript
1
star
95

stylish-es6

This is me thinking out loud on writing good lookin' ES6.
1
star
96

what-was-i-doing

find uncommitted changes in a directory of git repos
JavaScript
1
star
97

package-good

naive linter for npm's package.json
JavaScript
1
star
98

sublime-text-user

My personal Sublime Text 2 Settings
1
star
99

file-manager.js

file manager, written in JS.
1
star
100

angular-poppins

AngularJS config files for Mary Poppins
JavaScript
1
star