AngularJS tips and tricks – broadcast online and offline status

In continuing my experiments with AngularJS, I often stumble upon new challenges, I haven’t met before. One of these challenges was to broadcast the online and offline status of the browser.

I wanted to be able to hide different parts of the gui, if the user wasn’t online. In order to do that, I had to create a centralized variable, that would notify the gui whenever changes occurred. I did this by applying the following code in my app:$rootScope) {
      // console.log("online:" + navigator.onLine);

      $ = navigator.onLine ? 'online' : 'offline';

      if (window.addEventListener) {
        window.addEventListener("online", function() {
          $ = "online";
        }, true);
        window.addEventListener("offline", function() {
          $ = "offline";
        }, true);
      } else {
        document.body.ononline = function() {
          $ = "online";
        document.body.onoffline = function() {
          $ = "offline";

As you can see, the function adds an event listener that will automatically update the $ variable. Now, I can just use this variable in my HTML – like so:

<li ng-show="online == 'online'"><i class="icon-lock dark"></i><asp:LoginStatus ID="LoginStatus2" runat="server" LogoutText="Signout" LogoutPageUrl="~/Login.aspx" LoginText="Signout" LogoutAction="Redirect" /></li>

Works like a charm 🙂


6 thoughts on “AngularJS tips and tricks – broadcast online and offline status

  1. Actually listening for the window.navigator.onLine only gives you a status of your LAN / WIFI connection and doesn’t check for any internet connection (in order to achieve that, we have to make an additional ajax request when we think that we are online, depending on the status).
    a nice library that can save us the hassle –
    docs about –

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s