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:
app.run(function($rootScope) { // console.log("online:" + navigator.onLine); $rootScope.online = navigator.onLine ? 'online' : 'offline'; $rootScope.$apply(); if (window.addEventListener) { window.addEventListener("online", function() { $rootScope.online = "online"; $rootScope.$apply(); }, true); window.addEventListener("offline", function() { $rootScope.online = "offline"; $rootScope.$apply(); }, true); } else { document.body.ononline = function() { $rootScope.online = "online"; $rootScope.$apply(); }; document.body.onoffline = function() { $rootScope.online = "offline"; $rootScope.$apply(); }; } });
As you can see, the function adds an event listener that will automatically update the $rootScope.online 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
