AngularJS Chat Basic Tutorial

npm install

npm install angular-chat

bower install

bower install angular-chat

github install

git clone https://github.com/stephenlb/angularjs-chat.git
Welcome Visitor!
Share

</> tl;dr quick start code

On your phone, try AngularJS Chat Demo App. The demo app is more detailed than the quick start code. On the live stream overview we will cover more of these details. It's better to start simple. The following code will get you started. We will exclude the fancy CSS3 animations for now.

<!-- =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -->
<!-- includes -->
<!-- =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -->
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/rltm/web/rltm.js"></script>
<script src="bower_components/angular-chat/angular-chat.js"></script>

<!-- =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -->
<!-- configuration -->
<!-- =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -->
<script>
var chat = angular.module( 'BasicChat', ['chat'] );

angular.module('chat').constant('config', {
    rltm: {
        service: "pubnub",
        config: {
            publishKey: "demo",
            subscribeKey: "demo"
        }
        // or use socket.io!
        // https://github.com/pubnub/rltm.js#socketio
    }
});

</script>

<!-- =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -->
<!-- controller -->
<!-- =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -->
<script>
chat.controller('chat', ['Messages', '$scope', function(Messages, $scope) {

    // Message Inbox
    $scope.messages = [];
    // Receive Messages
    Messages.receive(function(message) {
        $scope.messages.push(message);
    });
    // Send Messages
    $scope.send = function() {
        Messages.send({ 
            data: $scope.textbox 
        });
    };
}]);
</script>

<!-- =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -->
<!-- view -->
<!-- =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -->
<div ng-app="BasicChat">
    <div ng-controller="chat">
        <div ng-repeat="message in messages">
            <strong>:</strong>
            <span></span>
        </div>
        <form ng-submit="send()">
            <input ng-model="textbox">
        </form>
    </div>
</div>

AngularJS Chat Tutorial

This tutorial is for you if you are a software developer. Specifically an Angular JS software developer. This walk-through is open source and free; MIT style. You can also get started with the AngularJS Chat GitHub repository. Or you can use NPM/Bower packages to acquire the dependencies you need to follow along. bower install angular-chat is the preferred. You can also use npm install angular-chat.

So why is chat important? Well for one thing, nothing kills customer experience more than when they can't communicate with a company when trying to purchase a product. A modern way to exceed expectations of your customer's experience is really simple. Chat communication. When your customers are seamlessly able to communicate with you, your sales and business metrics shift positively. Immediately obtaining information allows a customer to move forward with purchasing decisions with little effort. The customer's experience is streamlined. We humans use "chat" to communicate. Chat is what we are good at. And that makes things easy.

Guess what? We will be live streaming and live coding! The example AngularJS Chat app will be built live; with you watching. We will answer your questions live. You can get notified when we go live by subscribing here.

By subscribing you will able to receive updates when a live stream starts. We will talk about your frequently asked questions. Also best practices and cats maybe. You will be able to ask your questions live.

Building chat communication is difficult. There are a lot of challenges you need to overcome. Building chat applications with AngularJS is extremely rewarding. AngularJS allows for maintenance of your chat apps. That is because when you need to add new features to your Angular application; it's a breeze. With the upcoming Angular 2 framework the level of abstraction used to simplify your application development will make your life easy as the developer.

The purpose of this tutorial is to help you build AngularJS modules and extensions for chat communication. Soon you're application will allow your team to communicate with your users. Or maybe you want your users to talk to each other. Using both AngularJS 1.X and Angular 2 modules enables messaging experiences in your app on mobile iOS/Android and web. That is the goal of this walk-through.

We will start the code section of this walkthrough. And you will need the: AngularJS Chat GitHub Repository. You can also bower install angular-chat or npm install angular-chat. We are using bower in the example. Make sure to include your JavaScript dependency files.

<!-- =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -->
<!-- includes -->
<!-- =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -->
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/rltm/web/rltm.js"></script>
<script src="bower_components/angular-chat/angular-chat.js"></script>

<script>
    // AngularJS Chat Configuration
    var chat = angular.module( 'BasicChat', ['chat'] );
    angular.module('chat').constant('config', {
        rltm: {
            service: "pubnub",
            config: {
                publishKey: "YOUR_PUBLISH_API_KEY",
                subscribeKey: "YOUR_SUBSCRIBE_API_KEY"
            }
        }
    });
</script>

The angular-chat library uses rltm.js for chat network connectivity. Rltm.js can be configured to use either your own hosted Socket.io server or PubNub. We recommend setting up with PubNub to get started quickly and scale to infinity.

Now that you have the prerequisites including your PubNub API keys, we are ready for the next part. Here's an example on how to send and receive a message within your AngularJS app. First we will start with accessing the AngularJS Chat Model methods. This code is a simple controller.

// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// Minimal Chat Controller
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
chat.controller( 'chat', [ 'Messages', '$scope', function( Messages, $scope ) {
    // - - - - - - - - - - - - - - - - - -
    // Message Inbox
    // This array will hold the messages
    // ordered by receipt.
    // - - - - - - - - - - - - - - - - - -
    $scope.messages = [];

    // - - - - - - - - - - - - - - - - - -
    // Receive Messages
    // Push to Message Inbox.
    // - - - - - - - - - - - - - - - - - -
    Messages.receive(function(message) {
        $scope.messages.push(message);
    });

    // - - - - - - - - - - - - - - - - - -
    // Send Message
    // This is a controller method used
    // when a user action occurs.
    // Also we expect a model reference
    // ng-model="textbox".
    // - - - - - - - - - - - - - - - - - -
    $scope.send = function() {
        Messages.send({ 
            data: $scope.textbox 
        });
    };

} );

Wait was it really that easy? Boy howdy. There are a couple more things that you need to do in preparation to add chat in your application. It is good to know about the entry points of sending and receiving chat messages. Now you can send receive JSON messages. Oh right forgot to mention. The messages are automatically encoded in JSON for you!

A simple controller for messaging applications only needs one model reference: $scope.messages array. The messages array can hold all of the messages. And you can have them displayed on the application user interface. Anytime a new message arrives, it will be pushed into the messages array. When we apply this to an HTML view, messages will be displayed to the user. Here is the code for displaying Messages to the user.

<!-- =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -->
<!-- Chat View in HTML -->
<!-- =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -->
<div ng-app="BasicChat">
    <div ng-controller="chat">
        <div ng-repeat="message in messages">
            <strong>:</strong>
            <span></span>
        </div>
        <form ng-submit="send()">
            <input ng-model="textbox">
        </form>
    </div>
</div>

This simple AngularJS view has two parts. The first part is a messages display area. The second part is user input for sending messages. When a user submits their text, the controller will deliver this message for you using the Messages.send() method. Pretty neat, yah? You will also want to set user information along with that message payload. This is important because you need to identify who sends the message. You can do that by invoking the Messages.user() method.

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Set User Data
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Messages.user({ name : "Samus Aran" });

You can put anything inside the object that is JSON serializable. This information will become accessible with each message sent. You can display this information in the HTML view. Internally we call this information chat message meta data. It will remain associated with each message sent. As of this tutorial, older messages will retain the original meta data information. This means if a user updates their name or info that it will not be propagated to the older chat messages in the data model.

In the HTML view, you can access the user data like this:

<!-- =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -->
<!-- User Data in HTML View -->
<!-- =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -->
Your name is {{ message.user.name }}
The thing is {{ message.user.other_thing }}
Bar {{ message.user.foo }}

With all these parts combined you have a basic chat application! However it is not actually complete. There is more to be done in order to ensure excellent user experience. Super pretty UI is what I'm referring to. Beautiful user interfaces are helpful indeed. Our demo application includes some CSS3 snazziness. CSS3 animations and flex box are used in our basic AngularJS chat app. Guess what. It is 2016. We are now in the future. Browsers on modern operating systems include the ability to understand how to display flex box and render CSS3 animations. This makes our life easypeasy. Whoopee!

I like making pixel perfect user interfaces and experiences. Web browsers vendors with CSS3, HTML5 and JavaScript have not always provided a consistent user experience. But it's better now! You don't realize how awesome this makes your application development speed. I will work with you and show you what modern 2016 technology can yield in terms of awesomeness. We will start with only a preview for you.

Flex Box with AngularJS

<!-- =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -->
<!-- Flex Box Example -->
<!-- =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -->
<style>
    div.parent-container { display: flex; }
    div.child-span       { flex: 1;       }
</style>
<div class="parent-container">
    <div class="child-span"> 1 </div>
    <div class="child-span"> 2 </div>
    <div class="child-span"> 3 </div>
</div>

One of the modern technologies is flex box. If you have not used flex box before, you should! Before there was flex box you had to combine your HTML CSS and JavaScript to manipulate HTML elements to your layout desires. Now with flex box, the browser render engine will take care of this for you when you use a few CSS3 directives.

I thought flex box would end up being more complicated. But it is simple and works phenomenally for multiple screen sizes and media queries. Flex box fulfills my desire to maintain proper abstraction between the view layer the styling layer the controller and the model.




@media (max-width: 500px) {
    div.parent-container { flex-direction: column; }
}

Flex box for the win. You can change the order of display for elements. And you don't have to modify the HTML! Simplicity achieved. The alternative is a variety of CSS3 display type conditions. Flex box offers improved simplicity when you are programming for web and mobile apps.

We showed you a few key snippets of the basic chat application. You will want more beyond the basic chat experience for your users. That is why a more advanced application has been built for you to copy. Now you can get the source Code on GitHub. The GitHub repo has all the JavaScript and CSS ready. It is only a starting point though. There's more to come. The plan is to use the AngularJS 1.5 Chat Module as a starter for 2016. We'll be moving to Angular 2 maybe. This depends on popular demand.

There are many companies with chat. Many chat apps. They all do the chat thing. Some folks are chat exclusive. And some use chat to augment and improve user experience in the application. You can chat between live broadcasters and the audience members. Chat is fundamentally how we communicate as humans. Building chat applications is difficult. Now it is less difficult now that you have read this walkthrough.

Periscope and Meerkat

Periscope and Meerkat grant you the ability of teleportation. Distant places on Earth no longer apply. You now can join broadcasters in their experiences as they record video in realtime using their own phone. You get a chance to see what they see. Partly because they are potentially thousands of miles away there are only a few methods available for communicating with a broadcaster. Chat.

Chat enables viewers to communicate with the broadcaster. The broadcaster might be a journalist. A journalist filming political things, probably. You might want to ask questions to the broadcaster. Chat allows you to do this. Both Meerkat and Periscope include chat communication between broadcaster and viewer audience. Both of these Apps are native so they don't use AngularJS of course. However these apps could have been built with AngularJS in mind.

TwitchTV and YouTube LIVE!

I have been watching Twitch TV. It is entertaining as a gamer. I played SNES games and modern games. Like Super Metroid and aid Mega Man/X. And PlayStation with Resident Evil series and Final Fantasy series. I like watching streamers play these games. It's much easier to just hang back and turn on the stream rather than playing myself. This experience additionally includes the ability to chat with the gamer as they play live.

I don't often use the sidebar chat. I read the comments from the audience members. Chatting with the broadcasters is generally satisfying. I can imagine building these apps using AngularJS! Adding a sidebar chat experiences for audience interactivity is easy with angular-chat module.

Slack, Flowdock and BaseCamp

Working with my team at PubNub we communicate through team chat. Slack, Flowdock and BaseCamp are the most popular team chat applications. We also use Skype, Hangouts and a bit of SalesForce team chat. Primarily I use Flowdock and Slack in Engineering. Throughout the day other teams use BaseCamp. Are you starting to see why chat is such a big deal for humans in 2016?

These apps are HTML browser-based applications for group chat. They all have mobile apps. So you can communicate with your team with mobile app chat too. I would definitely build a Slack chat clone using AngularJS.

Intercom, Olark, UserVoice and Help Desk Support

There are a lot of situations when customer support is dissatisfying. Having chat on your app or on your website has proven to increase customer interactivity with the business. As a developer I don't talking to a sales guys. That sales guy has an agenda. I don't want to hear it. But if I have a question, I always ask support for help.

If I see a chat option available, I will always use chat to contact customer support. This style of interaction is one of the best qualifiers for a prospect conversion. If your business is online, like anapp or website, make sure you have chat interactivity. Customer support typically falls in the category of one-to-one chat.

WhatsApp and Snapchat

We are in the process of replacing SMS with OTT (over-the-top) messaging. This is allowing users to communicate using phone numbers as their identity without the SMS price tag. A pretty smart idea for an app, right? It appears that WhatsApp was able to accomplish this. They were able to defeat SMS and offer IP messaging at an unbeatable price. They've built a simple chat application making it easy for people to text each other. Really this is the most basic example of chat.

I wonder why Skype wasn't able to accomplish this. I suppose Skype, WhatsApp and SnapChat are targeted at different use case patterns. Like the customer support use case, WhatsApp and SnapChat use the one-to-one chat model.

Instacart and Eat24

There are more chat applications yet. We haven't covered doctor-patient communication. This requires HIPAA compliance, privacy and encryption security. There's also food order/delivery services that allow you to check on your delivery status on your Instacart and Eat24 orders. We also have DoorDash, SpoonRocket and PostMates. These applications mutually benefit the customer and business when using chat mechanisms to support staff and customers.

Life is easy. You get freebies by importing an AngularJS Module. One of the more difficult things to get right in application development is security. Security is included by default. And it's for free! Just like singing. Signing is for free too. Communication security is paramount in human chat applications. AES cryptography and TLS termination help secure and encrypt user communication over the WAN. In addition to message body encryption you also have to deal with message integrity and identity verification of the sender.

How can you tell if the sender really is who they say they are? You need to able to confirm their identity. The best way to do that is through message signatures. You can also call these digital signatures. This is done by generating and maintaining a secret on the client. Then you share a public key maintained by an identity verification service. Note that we have not included this feature by default. We will upon popular demand.

Don't forget about identity authentication and authorization. Authentication occurs when a user logs into their account using an email/password challenge. This is known as "authenticating a user". After a user has been authenticated, they will receive a token known as a session ID. This session ID is a long and unpredictable string of randomized characters.

Example Session ID: ZVRjEIUFRxSw1FV WhRBVtRFZ9jbW89

This session ID will be included in every REST service call. Each service call is then authorized using the session ID. This is a process called authorization. If the session ID is valid, the user permissions associated will be checked. If permission records allow, a successful payload is sent/received.

Even though it is the future now, where we have hover boards and flying cars, Internet connectivity is often spotty. Internet is unreliable in many situations. Especially when driving. Or when walking around in the shopping mall. You need a reliable data stream network to provide message delivery. Even when your Internet disconnects your messages will still be delivered. This is called message recovery after reconnect. There are many mechanisms for message redelivery. In high scale networking this type of recovery is "oh dear molly that's tricky." By default the best option is included for you in the AngularJS chat module.

Long-term message storage requires a different technical solution than short-term message redelivery. The AngularJS module also uses PubNub to help solve for this need. They have an infrastructure built with fault tolerance in mind. Essentially many copies over different geographical regions. PubNub maintains 20+ data centers that hold copies of your chat messages, encrypted on a secure data stream network. AngularJS chat will invoke a REST call to the closest of the 20 data centers and receive historical message chat history. By default this is disabled.

Doherty Threshold

You may have noticed in the test chat application that message delivery is light speed. This is because we are using a data stream network called PubNub. The network leverages many POPs (points of presence) around the planet to transmit secure messages in less than a quarter of a second.

When we talk about the Doherty Threshold we are referencing appoint less than 400ms where human perception of real-time begins. Being able to accomplish instantaneous delivery of chat messages is a cool capability that data stream networks provide.

I'm looking forward to building the next phases of AngularJS chat. More to come. The plan is to begin building and replicating well-known chat applications. Some of them were mentioned in this walk-through. Subscribe and follow below to receive the next walk-through. Also if you're reading before the live stream, you should subscribe and follow to receive a notification when the live stream starts on YouTube.

What would you like to see next? Share your comments below.

  1. How to launch your Chat App on Apple/Google App Stores
  2. Twitch TV Chat in AngularJS
  3. An Angular 2 Chat Module
  4. More Features for Basic App: 1-to-1 Chat, Global Broadcast Notifications, etc.

Share your comments below.

Share