---
source_url: https://www.pubnub.com/docs/sdks/angular
title: AngularJS API & SDK Docs 4.2.0
updated_at: 2026-05-27T17:01:31.024Z
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# AngularJS API & SDK Docs 4.2.0

:::warning 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](https://www.pubnub.com/docs/sdks/javascript) 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](https://www.pubnub.com/docs/chat/chat-sdk) which provides higher-level abstractions.
Legacy contributions are [welcome on GitHub](https://github.com/pubnub/pubnub-angular).
:::

## Get code

[https://github.com/pubnub/pubnub-angular/releases](https://github.com/pubnub/pubnub-angular/releases)

## Get code: CDN

### Latest stable version

[https://cdn.pubnub.com/sdk/pubnub-angular/pubnub-angular-.js](https://cdn.pubnub.com/sdk/pubnub-angular/pubnub-angular-4.2.0.js)

### Latest stable minified version

[https://cdn.pubnub.com/sdk/pubnub-angular/pubnub-angular-4.2.0.min.js](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](https://github.com/pubnub/pubnub-angular/tree/master/dist)

## Get code: bower

:::warning Bower Deprecated
Bower has been deprecated since 2017. For new projects, use the [JavaScript SDK](https://www.pubnub.com/docs/sdks/javascript) directly with modern Angular applications.
:::

```bash
bower 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 `Pubnub` service.
* 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:

1. Include AngularJS: 1<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
2. Include the latest version of PubNub's Javascript SDK
3. 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:

```javascript
<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:

```javascript
<script src="scripts/app.js"></script>
```

Inside `app.js`, add an AngularJS dependency on the PubNub AngularJS library (`Pubnub.angular.service`):

```javascript
angular.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:

```javascript
<script src="scripts/controllers/main.js"></script>
```

The AngularJS Pubnub service is injected into the controller as follows:

```javascript
.controller('MainCtrl', function($scope, Pubnub) { ... });
```

### Differences in usage with native JavaScript SDK

To learn about Pubnub JavaScript features refer to native [Pubnub JavaScript SDK](https://www.pubnub.com/docs/sdks/javascript) 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.
:::

```javascript
var defaultInstance = new PubNub({
    publishKey: 'your pub key',
    subscribeKey: 'your sub key'
});

defaultInstance.publish(
    {
        message: {
            such: 'Hello!'
        },
        channel: 'myChannel'
    },
    function (status, response) {
        if (status.error) {
            console.log(status)
        } else {
            console.log("message Published w/ timetoken", response.timetoken)
        }
    }
);
```

#### Second 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.
:::

```javascript
Pubnub.init({
    publishKey: 'your pub key',
    subscribeKey: 'your sub key'
});

Pubnub.publish(
    {
        message: {
            such: 'Hello!'
        },
        channel: 'myChannel'
    },
    function (status, response) {
        if (status.error) {
            console.log(status)
        } else {
            console.log("message Published w/ timetoken", response.timetoken)
        }
    }
);
```

That'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.
:::

```javascript
var helloWorldApp = angular.module('helloWorld', ['pubnub.angular.service']);

helloWorldApp.run(['Pubnub', function (Pubnub) {
    Pubnub.init({
        publishKey : 'demo',
        subscribeKey : 'demo'
    });
}]);

helloWorldApp.controller('HelloCtrl', ['$scope', 'Pubnub', function($scope, Pubnub) {
    $scope.subscribe = function () {
        Pubnub.subscribe({
            channel: 'hello_world',
            triggerEvents: ['message']
        })
    }
}]);

helloWorldApp.controller('WorldCtrl', function($scope, $rootScope, Pubnub) {
    $rootScope.$on(Pubnub.getMessageEventNameFor($scope.selectedChannel), function (ngEvent, envelope) {
        $scope.$apply(function () {
            // add message to the messages list
            $scope.chatMessages.unshift(envelope.message);
        });
    });

    $rootScope.$on(Pubnub.getEventNameFor('publish', 'callback'), function (ngEvent, status, response) {
        $scope.$apply(function () {
            if (status.error){
               $scope.statusSentSuccessfully = false;
            } else {
               $scope.statusSentSuccessfully = true;
            }
         })
    });
});
```

## Events

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:

```javascript
Pubnub.subscribe({
    channels  : [$scope.selectedChannel],
    channelGroups: [$scope.selectedChannelGroup],
    withPresence: true,
    triggerEvents: ['message', 'presence', 'status']
});
```

You can also enable all possible events using `triggerEvents: true`.

#### Listening to a message event of a specific channel or channel group:

```javascript
$rootScope.$on(Pubnub.getMessageEventNameFor($scope.selectedChannel), function (ngEvent, envelope) {
    $scope.$apply(function () {
        // add message to the messages list
        $scope.chatMessages.unshift(envelope.message);
    });
});
```

#### Listening to a Presence event of a specific channel or channel group:

```javascript
$rootScope.$on(Pubnub.getPresenceEventNameFor($scope.selectedChannel), function (ngEvent, pnEvent) {
    // apply presence event (join|leave) on users list
    handlePresenceEvent(pnEvent);
});
```

#### 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](https://www.pubnub.com/docs/sdks/angular/api-reference/publish-and-subscribe#listeners)

```javascript
$rootScope.$on(Pubnub.getEventNameFor('subscribe', 'status'), function (ngEvent, status, response) {
    if (status.category == 'PNConnectedCategory'){
        console.log('successfully connected to channels', response);
    }
});
```

### 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:

* `callback` function in method arguments
* `triggerEvents: ['callback']`
* `triggerEvents: true` (will trigger all the events of the method)

#### Triggering the events:

##### Method with callbacks as argument

```javascript
Pubnub.publish(
    {
        channel: 'myChannel',
        message: 'Hello!'
    },
    function(status, response){
        console.log(response);
    }
);
```

##### Method with events triggered

```javascript
Pubnub.publish({
    channel: 'myChannel',
    message: 'Hello!',
    triggerEvents: ['callback']
})
```

#### 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:

```javascript
$rootScope.$on(Pubnub.getEventNameFor('publish', 'callback'),
    function (ngEvent, status, response) {
        $scope.$apply(function () {
            if (status.error){
                $scope.statusSentSuccessfully = false;
            } else {
               $scope.statusSentSuccessfully = true;
            }
        })
    }
);
```

## 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

**Init Pubnub:** [](#init-pubnub)

```javascript
Pubnub.init({
    publishKey: 'your pub key',
    subscribeKey: 'your sub key'
});
```

**Inject the $pubnubChannel service in a controller:** [](#inject-pubnub-channel-object)

```javascript
.controller('ScoresCtrl', function($scope, $pubnubChannel) { ... });
```

**Bind the $pubnubChannel object to a scope variable providing a channel name and some optional parameters:** [](#bind-pubnub-channel-object)

```javascript
.controller('ScoresCtrl', function($scope, $pubnubChannel) {
    $scope.scores = $pubnubChannel('game-scores-channel',{ autoload: 50 })
});
```

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:

```javascript
<body ng-app="app" ng-controller="ScoresCtrl">
    <ul class="collection">
        <li ng-repeat="score in scores">{{score.player}}<li>
    </ul>
</body>
```

### Optional config parameters

You can pass in some optional parameters in the config hash when instantiating the `$pubnubChannel`:

```javascript
$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: false If autosubscribe is enabled, subscribe and trigger the presence events, default: false
* instance: deluxeInstance The instance that will be used: default: {default PubNub instance}

### Available methods

You can interact with the `$pubnubChannel` via dedicated methods:

```javascript
.controller('ScoresCtrl', function($scope, $pubnubChannel) {
    $scope.scores = $pubnubChannel('game-scores-channel',{ autoload: 20 })
    $scope.scores.$publish({player: 'John', result: 32}) // Publish a message in the game-scores-channel channel.
});
```

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.

### Wrapping the $pubnubChannel object in a service

Instead of using the `$pubnubChannel` directly in a controller you can wrap it into a Service:

```javascript
app.factory("Scores", ["$pubnubChannel",
    function($pubnubChannel) {

        var config = {
            instance: 'myAnotherPubNubInstanceName', // By default, the default PubNub instance
            autoload: 50 // Autoload the channel with 50 messages (should be < 100)
        }
        return $pubnubChannel('game-scores-channel', config);
    }
]);
```

And use the Scores service in a controller:

```javascript
app.controller("ScoresCtrl", ["$scope", "Scores", function($scope, Scores) {
    $scope.messages = Scores();
]);
```

### Extending the $pubnubChannel object

You can also extend the `$pubnubChannel` object using the `$extend` method in order to add or override methods:

```javascript
angular.module('app').factory('Scores',
    ['$pubnubChannel',function ScoresService($pubnubChannel) {

        // We create an extended $pubnubChannel channel object that add a additionnal sendScore method
        // that publish a score with the name of the player preloaded.
        var Scores = $pubnubChannel.$extend({
            sendScore: function(score) {
                return this.$publish({
                    player: 'John',
                    score: score
                })
            }
        });

        return Scores('game-scores-channel', {autoload: 30});

    }]
);
```

You can then use the Scores service in a controller:

```javascript
app.controller("ScoresCtrl", ["$scope", "Scores", function($scope, Scores) {
    $scope.scores = Scores();
    $scope.scores.sendScore(34);
]);
```

## The $pubnubChannelGroup object

The `$pubnubChannelGroup` 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 using the `$channel`(channelName) method.

### Getting started

**Init Pubnub:** [](#init-pubnub-2)

```javascript
Pubnub.init({
    publishKey: 'your pub key',
    subscribeKey: 'your sub key'
});
```

**Inject the $pubnubChannelGroup service in a controller:** [](#inject-pubnub-channel-group-object)

```javascript
.controller('ChatCtrl', function($scope, $pubnubChannelGroup) { ... });
```

Instantiate a `$pubnubChannelGroup` object and assign it to a scope variable providing a channel group name and some optional parameters.

```javascript
.controller('ChatCtrl', function($scope, $pubnubChannelGroup) {
    $scope.Conversations = $pubnubChannelGroup('conversations-channel-group')
    // Fetch a $pubnubChannel from the Conversations $pubnubChannelGroup object
    $scope.currentConversation = $scope.Conversations.$channel('conversation-178')
    // $scope.messages is a $pubnubChannel, you can use any method available for a $pubnubChannel
    $scope.currentConversation.$load(20)
});
```

### Optional config parameters

You can pass in some optional parameters in the config hash when instantiating the `$pubnubChannelGroup`:

```javascript
$scope.Conversation = $pubnubChannelGroup('conversations-channel-group', config)
```

* autosubscribe: true Automatically subscribe to the channel, default: true
* presence: false If autosubscribe is enabled, subscribe and trigger the presence events, default: false
* instance: deluxeInstance The instance that will be used: default: {default PubNub instance}
* channelExtension: {foo: function(){ return "bar"}} // Define or override methods for the channels returned when calling $channel on the $channelGroup object.

### Methods available

`$channel`(channel) Return a `$pubnubChannel` object which is containing the messages received via the channel group

### Wrapping the $pubnubChannelGroup object in a service

Instead of using the `$pubnubChannelGroup` directly in a controller you can wrap it into a Service:

```javascript
app.factory("Conversations", ["$pubnubChannelGroup",
    function($pubnubChannelGroup) {
        return $pubnubChannelGroup('conversations-channel-group');
    }
]);
```

And use the Conversation service in a controller:

```javascript
app.controller("ChatCtrl", ["$scope", "Conversation", function($scope, Conversation) {
    $scope.currentConversation = Conversations.$channel('conversation-13345');
]);
```

### Extending channels of a $pubnubChannelGroup

When instanciating a `$pubnubChannelGroup`, you can pass in a channelExtension parameter that allows you to add or override methods for the `$pubnubChannel` objects that is returned when calling the `$channel`(channelName) method.

```javascript
app.controller("ChatCtrl", ["$scope","$pubnubChannelGroup", function($scope, $pubnubChannelGroup) {

    // We add a sendMessage methods that publish a message with an already defined payload.
    var channelExtension = {
        sendMessage: function(messageContent) {
            return this.$publish({ content: messageContent, sender: "Tomomi" })
        }
    }
    $scope.Conversations = $pubnubChannelGroup('channelGroup', {channelExtension: channelExtension});
    $scope.currentConversation = $scope.Conversations.$channel('conversation-123')
    // Sending a message via the extra method added to the channel.
    $scope.currentConversation.sendMessage('Hello!')

]);
```

## Copy and paste examples

In addition to the Hello World sample code, we also provide some copy and paste snippets of common API functions:

### Init

Instantiate a new Pubnub instance. Only the `subscribeKey` is mandatory. Also include `publishKey` if you intend to publish from this instance, and the `secretKey` if you wish to perform Access Manager administrative operations from this AngularJS instance.

:::warning Important
It is not a best practice to include the `secretKey` in client-side code for security reasons.
When you init with `secretKey`, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.
:::

:::note
Set `restore` to `true` to allow catch-up on front-end applications.
:::

:::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.
:::

```javascript
Pubnub.init({
    subscribeKey: "mySubscribeKey",
    publishKey: "myPublishKey",
    uuid: "myUniqueUUID",
    ssl: true
})
```

### Subscribe

Subscribe (listen on) a channel (it's async!):

```javascript
// Subscribe to a channel
Pubnub.addListener({
    status: function(statusEvent) {
        if (statusEvent.category === "PNUnknownCategory") {
            var newState = {
                new: 'error'
            };
            Pubnub.setState(
                {
                    state: newState
                },
                function (status) {
                    console.log(statusEvent.errorData.message)
                }
            );
        }
    },
    message: function(message) {
        console.log(message)
    }
})

Pubnub.subscribe({
    channels: ['my_channel']
});
```

### Publish

Publish a message to a channel:

```javascript
Pubnub.publish(
    {
        message: {
            such: 'Hello from the PubNub Javascript SDK!'
        },
        channel: 'my_channel'
    },
    function (status, response) {
        if (status.error) {
            // handle error
            console.log(status);
        } else {
            console.log("message Published w/ timetoken", response.timetoken);
        }
    }
);
```

### Here now

Get occupancy of who's `here now` on the channel by UUID:

:::note
Requires you to enable the `Presence` add-on for your key. Refer to the [How do I enable add-on features for my keys?](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) knowledge base article for details on enabling features.
:::

```javascript
Pubnub.hereNow(
    {
        channels: ["ch1"],
        channelGroups : ["cg1"],
        includeUUIDs: true,
        includeState: true
    },
    function (status, response) {
        // handle status, response
    }
);
```

### Presence

Subscribe to real-time Presence events, such as `join`, `leave`, and `timeout`, by UUID. Setting the presence attribute to a callback will subscribe to presents events on `my_channel`:

:::note
Requires you to enable the `Presence` add-on for your key. Refer to the [How do I enable add-on features for my keys?](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) knowledge base article for details on enabling features.
:::

```javascript
Pubnub.addListener({
    presence: function(m){
        console.log(m)
    },
    message: function(message) {
        console.log(message)
    }
})

Pubnub.subscribe({
    channels: ["my_channel"],
    withPresence: true
});
```

### History

Retrieve published messages from archival storage:

:::note
Requires that the `Message Persistence` add-on is enabled for your key. How do I enable add-on features for my keys? - see [https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-)
:::

```javascript
Pubnub.history(
    {
        channel: 'history_channel',
        count: 100, // 100 is the default
        stringifiedTimeToken: true // false is the default
    },
    function (status, response) {
        // handle status, response
    }
);
```

### Unsubscribe

Stop subscribing (listening) to a channel.

```javascript
// Unsubscribe from 'my_channel'

Pubnub.unsubscribe({
    channels : ['my_channel']
});
```