Home / AngularJS / Private messaging with socket.io and angularjs

Private messaging with socket.io and angularjs

Private messaging is a familiar concept that everybody has knowledge of but most of the novice developers are lost while developing one. In this tutorial I have chosen socket.io and angularjs. Socket.io helps in transmitting data realtime while angularjs (MVC framework) is tightly coupled with data-binding along with DOM manipulation which jQuery does. Believe me, its time for you to switch to angularjs. Angularjs 1.5 also supports jQLite that’s an added advantage!

Learn angularjs now! It’s now or never!

Just do it!

– It’s worth learning!

Setup

Let’s first setup necessary modules on server and client side

* Server side – NodeJS and socket.io server
* Client side – socket.io.js

I assume your environment is ready for the development therefore jumping on to the design section. If you are not familiar with NodeJS set up read my first tutorial on NodeJS and socket.io

Mark up (HTML + Angular view)

There is a huge difference between how jQuery and AngularJS works. jQuery’s data binding works by manipulating the DOM elements whereas AngularJS listens only for data changes. Here is a very small example of data binding with jQuery and AngularJS.

jQuery data binding

AngularJS data binding

From the two examples you may notice that AngularJS doesn’t use HTML tag, class or ID to select an element but simply bind data where ever required. So less classes, less IDs and less junky HTML 😉

So here is how the design code looks (This design was grabbed from here. No worries you can use it in any kind of project. Check the license in source code.)

This is going to be a one page app (login + chat page). Don’t get horrified by new syntax. AngularJS is easier to understand than jQuery. This is my folder structure.

folder-structure-private-chat

1. index.html – Will load login.html and chat.html whenever required. All the CSS and JS files are preloaded here.
2. login.html – Has the HTML code for login form
3. chat.html  – Has the HTML code for chat module
4. app.js     – Server side socket script

index.html

The ng-app directive in the HTML tag is mandatory for any Angular app. This directive tells that the document is an Angular app and AngularJS starts running automatically.

The ng-view directive is used to load templates into the main view (in our case index.html). Whenever the route in the URL changes the corresponding template is loaded in the ng-view directive. For routes to work you need to include the angular-route.js

We have now prepared the main layout (index.html). We should now initialize AngularJS.

index.js

Here we initialize the angular module on ‘chatApp’ as defined in the ng-app directive. The second parameter accepts an array of value each being a method. We call this method injection. ngRoute method will allow the angular app to change views based on URL parameters. Now that we got our app initialized let us configure routes for login and chat page.

So when the URL has no additional parameters we load the login page into view and AuthController will run. When the URL has a parameter ‘/chat’ we load the chat page into view that will run the ChatController and if anything else is passed we redirect the user to the login page.

Let’s design the login page and write AuthController first,

login.html

ng-model is used to bind the values of HTML controls (input, textarea, radio, etc..) You will understand its use while writing the Controller.
ng-click directive is similar to the click event in jQuery except that it runs in angularjs. So when a user clicks the login button the login function inside the AuthController is triggered.

AuthController

$scope is used to access all the variables and functions within its controller. So we can get the nickname and email of the user by its model name (ng-model) like this $scope.nickname and $scope.email. The function $scope.login is called when login button is clicked. This shouldn’t be so hard to understand if you are familiar with basic javascript.

If validation passes in the login function call the connect function. I have used gravatar to display avatar of users by getting their email for this we need to encrypt the email to MD5 hash. I have used CryptoJS to perform this encryption CryptoJS.MD5($scope.email). Now we need to pass every user’s nickname and email hash to the socket server using socket.emit(‘newuser’)

Server side – app.js

Check if the nickname already exist on the server side and return the callback status with either false if already exist or true if not. Also when the status is true you need to do three things,

1. Push the nickname, emailhash and the socketid (unique connection id: socket.id) to an array.
2. Emit the users array back to the client (Note that I have delayed the response 1000 ms. This is to make sure that the chat page is fully loaded and ready).

So when the chat page is loaded when status is true the server will send the users array back to client after a delay of 1000ms. Now we need to update the view with data from response. The beauty of AngularJS is that you can format data without even using javascript or jQuery. You may also write complicated expressions like nested ternary operation and much more!. I hope you will love it.

I will explain each module in chat individually but not in detail. You can understand the code by spending some time with it or else you will get bored.

* Populate online users and set search filter

chat-explanation-module1

This directive takes array as an input and repeats the element for all items in the array. The array users is set in the ChatController. The filter option takes an input and it searches for the match in the element when searchUsers variable changes. In our case I have used ng-model for searchUsers variable. So when the user start typing in the search box this filter is triggered. You don’t have to use jQuery or plugins to iterate and search for available users.

* Use gravatar to show avatars of each user and this can be achieved by calling the URL,

* Load conversation of user. The conversation array is set in the ChatController

* Textarea for writing message with validation

Every time after a key is pressed we need to check if the ‘Enter’ key alone is pressed. If condition is satisfied trigger the sendMessage function. This is achieved using the ng-keyup directive.

ChatController

Finally run the socket server

run-node

Feel free to raise questions in the comments section I’ll proactively respond to your comments.

Download

About Ashik

I am a Full Stack Developer and love to work on APIs and Apps. Hardcore lover of Ionic and Laravel <3

Check Also

Private chatroom using socket.io and NodeJS

In this tutorial I will teach you how to create a chatroom using SOCKET.IO and …

Do you wan't to get notified?

I will not spam your inbox. I will only send email whenever I publish a new article or to share information about technology

You have Successfully Subscribed!