AngularJS API & SDK Docs 4.2.0
Unsupported SDK
PubNub no longer supports this SDK. AngularJS (1.x) reached end-of-life in January 2022.
For new projects, use the JavaScript SDK directly with modern Angular (v2+). The JavaScript SDK works seamlessly with Angular's dependency injection and can be wrapped in a service for easy use across components. For chat applications, consider the Chat SDK which provides higher-level abstractions.
Legacy contributions are welcome on GitHub.
Get code
https://github.com/pubnub/pubnub-angular/releases
Get code: CDN
Latest stable version
https://cdn.pubnub.com/sdk/pubnub-angular/pubnub-angular-.js
Latest stable minified version
https://cdn.pubnub.com/sdk/pubnub-angular/pubnub-angular-4.2.0.min.js
Get code: source
https://github.com/pubnub/pubnub-angular/tree/master/dist
Get code: bower
Bower Deprecated
Bower has been deprecated since 2017. For new projects, use the JavaScript SDK directly with modern Angular applications.
1bower install --save pubnub pubnub-angular
Hello World
Pubnub Angular service is a wrapper for PubNub JavaScript SDK that adds a few extra features to simplify Angular integrations:
- Multiple instance behavior: All instances are accessible throughout application via
Pubnubservice. - Events: Delegated methods accept the triggerEvents option which will broadcast certain callback as an AngularJS event.
- A $pubnubChannel object that seamlessly binds a PubNub channel to a scope variable that gets updated with real-time data and allows you to interact with the channel through dedicated methods.
- A $pubnubChannelGroup object that provides an easy-to-use interface for channel groups. It stores the incoming messages in containers split by the channel and exposes an interface to directly fetch messages by channel.
You can still use the native Pubnub JavaScript SDK if you feel this will be more suitable for your situation.
Integrating PubNub AngularJS SDK into your App
Your HTML page will include 2 key libraries:
- PubNub JavaScript SDK
- PubNub JavaScript SDK AngularJS Service
To utilize this wrapper, include the scripts in the following order:
-
Include AngularJS:
1<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script> -
Include the latest version of PubNub's Javascript SDK
-
Include PubNub's AngularJS SDK:
1<script src="<location-of-PubNub-SDK>/pubnub-angular-4.2.0.min.js"></script>
We presume your app is already AngularJS-enabled with an ng-app attribute or the equivalent:
1<body ng-app="PubNubAngularApp">
Where PubNubAngularApp is the name of the AngularJS module containing your app.
We presume the code for the app lives in:
1<script src="scripts/app.js"></script>
Inside app.js, add an AngularJS dependency on the PubNub AngularJS library (Pubnub.angular.service):
1angular.module('PubNubAngularApp', ["pubnub.angular.service"])
This will make sure that the PubNub object is available to get injected into your controllers.
We presume the code for your controllers lives in:
1<script src="scripts/controllers/main.js"></script>
The AngularJS Pubnub service is injected into the controller as follows:
1.controller('MainCtrl', function($scope, Pubnub) { ... });
Differences in usage with native JavaScript SDK
To learn about Pubnub JavaScript features refer to native Pubnub JavaScript SDK manual. All methods of this SDK are wrapped with Pubnub AngularJS Service
Native Pubnub JavaScript SDK provides instance creation using Pubnub.init(), which returns new instance with given credentials. In Pubnub AngularJS SDK instances are hidden inside service and are accessible via instance getter. Methods of default instance are mapped directly to Pubnub service just like Pubnub.publish({...}). In most use cases usage of the only default Pubnub instance will be enough, but if you need multiple instances with different credentials, you should use Pubnub.getInstance(instanceName) getter. In this case publish method will looks like Pubnub.getInstance(instanceName).publish({}).
To summarize above let's check out the following 2 examples. Both of them performs the same job - creation of 2 Pubnub instances with different credentials. Publish method is invoked on the defaultInstance and grant method on anotherInstance
First example shows how to do that using native PubNub JavaScript SDK
Note
Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.
1var defaultInstance = new PubNub({
2 publishKey: 'your pub key',
3 subscribeKey: 'your sub key'
4});
5
6defaultInstance.publish(
7 {
8 message: {
9 such: 'Hello!'
10 },
11 channel: 'myChannel'
12 },
13 function (status, response) {
14 if (status.error) {
15 console.log(status)
show all 20 linesSecond example shows how to use PubNub AngularJS SDK for these purposes:
Note
Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.
1Pubnub.init({
2 publishKey: 'your pub key',
3 subscribeKey: 'your sub key'
4});
5
6Pubnub.publish(
7 {
8 message: {
9 such: 'Hello!'
10 },
11 channel: 'myChannel'
12 },
13 function (status, response) {
14 if (status.error) {
15 console.log(status)
show all 20 linesThat's it - you're ready to start using the PubNub AngularJS SDK!
Hello World example
Note
Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.
1var helloWorldApp = angular.module('helloWorld', ['pubnub.angular.service']);
2
3helloWorldApp.run(['Pubnub', function (Pubnub) {
4 Pubnub.init({
5 publishKey : 'demo',
6 subscribeKey : 'demo'
7 });
8}]);
9
10helloWorldApp.controller('HelloCtrl', ['$scope', 'Pubnub', function($scope, Pubnub) {
11 $scope.subscribe = function () {
12 Pubnub.subscribe({
13 channel: 'hello_world',
14 triggerEvents: ['message']
15 })
show all 36 linesEvents
Another key feature of this SDK is the ability to trigger method events in addition to passed in callbacks. By default events will not be triggered.
To enable all possible events for certain method, add triggerEvents: true option to the method arguments.
Triggering and listening to events for the subscribe method
With JavaScript V4, you can trigger 3 different events (message, presence and status)
Triggering the events:
1Pubnub.subscribe({
2 channels : [$scope.selectedChannel],
3 channelGroups: [$scope.selectedChannelGroup],
4 withPresence: true,
5 triggerEvents: ['message', 'presence', 'status']
6});
You can also enable all possible events using triggerEvents: true.
Listening to a message event of a specific channel or channel group:
1$rootScope.$on(Pubnub.getMessageEventNameFor($scope.selectedChannel), function (ngEvent, envelope) {
2 $scope.$apply(function () {
3 // add message to the messages list
4 $scope.chatMessages.unshift(envelope.message);
5 });
6});
Listening to a Presence event of a specific channel or channel group:
1$rootScope.$on(Pubnub.getPresenceEventNameFor($scope.selectedChannel), function (ngEvent, pnEvent) {
2 // apply presence event (join|leave) on users list
3 handlePresenceEvent(pnEvent);
4});
Listening to the global status events:
Via the status listener, you can receive different events such as when the network is online (PNNetworkUpCategory), when the SDK is connected to a set of channels (PNConnectedCategory), etc... See the list of events available in the API Reference
1$rootScope.$on(Pubnub.getEventNameFor('subscribe', 'status'), function (ngEvent, status, response) {
2 if (status.category == 'PNConnectedCategory'){
3 console.log('successfully connected to channels', response);
4 }
5});
Triggering and listening to events for the methods with callbacks
You have the possibility to trigger events for the methods with callbacks.
For the required callbacks, for ex. the callback called callback in the publish method, you should add it using one of the following ways:
callbackfunction in method argumentstriggerEvents: ['callback']triggerEvents: true(will trigger all the events of the method)
Triggering the events:
Method with callbacks as argument
1Pubnub.publish(
2 {
3 channel: 'myChannel',
4 message: 'Hello!'
5 },
6 function(status, response){
7 console.log(response);
8 }
9);
Method with events triggered
1Pubnub.publish({
2 channel: 'myChannel',
3 message: 'Hello!',
4 triggerEvents: ['callback']
5})
Listening to the events:
You can listen to the events that have been triggered using the Pubnub.getEventNameFor(...) helper from anywhere in your app. Params order in broadcasted events is the same as in native SDK methods, except that ngEvent object is prepended as the first param.
callback event will be triggered for both successful and unsuccessful response:
1$rootScope.$on(Pubnub.getEventNameFor('publish', 'callback'),
2 function (ngEvent, status, response) {
3 $scope.$apply(function () {
4 if (status.error){
5 $scope.statusSentSuccessfully = false;
6 } else {
7 $scope.statusSentSuccessfully = true;
8 }
9 })
10 }
11);
The $pubnubChannel object
The $pubnubChannel object allows you to seamlessly bind a PubNub channel to a scope variable, which gets automatically updated when there is new real-time data published in that channel. It also lets you interact directly with the channel by calling dedicated methods available into the $scope variable bound to the $pubnubChannel object.
Getting started
1Pubnub.init({
2 publishKey: 'your pub key',
3 subscribeKey: 'your sub key'
4});
Inject the $pubnubChannel service in a controller:
1.controller('ScoresCtrl', function($scope, $pubnubChannel) { ... });
Bind the $pubnubChannel object to a scope variable providing a channel name and some optional parameters:
1.controller('ScoresCtrl', function($scope, $pubnubChannel) {
2 $scope.scores = $pubnubChannel('game-scores-channel',{ autoload: 50 })
3});
Instantiating the $pubnubChannel is the only step needed to have a scope variable that reflects the real-time data from a channel. It subscribes to the channel for you, load initial data if needed and receive new real-time data automatically.
Display the $scope.scores variable in your view and you will see the data being loaded and updated when new data is received in that channel:
1<body ng-app="app" ng-controller="ScoresCtrl">
2 <ul class="collection">
3 <li ng-repeat="score in scores">{{score.player}}<li>
4 </ul>
5</body>
Optional config parameters
You can pass in some optional parameters in the config hash when instantiating the $pubnubChannel:
1$scope.scores = $pubnubChannel('game-scores-channel', config)
-
autoload: 50 The number of messages (<100) we want to autoload from history, default: none. -
autosubscribe: true Automatically subscribe to the channel, default:true -
presence:falseIf autosubscribe is enabled, subscribe and trigger the presence events, default:false -
instance:deluxeInstanceThe instance that will be used: default: {default PubNub instance}
Available methods
You can interact with the $pubnubChannel via dedicated methods:
1.controller('ScoresCtrl', function($scope, $pubnubChannel) {
2 $scope.scores = $pubnubChannel('game-scores-channel',{ autoload: 20 })
3 $scope.scores.$publish({player: 'John', result: 32}) // Publish a message in the game-scores-channel channel.
4});
Here are some methods you can use:
-
$publish(messages): Publish a message into the channel, return a promise which is resolved when the data is published or rejected when there is an error. -
$load(numberOfMessages): Load a number of messages from history into the array, return a promise resolved when the data is loaded and rejected if there is an error. -
$allLoaded(): Return a boolean to indicate if all the messages from history have been loaded.