Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

How to check internet connection in AngularJs

This is how I would check internet connection in vanilla javascript:

setInterval(function(){
    if(navigator.onLine){
        $("body").html("Connected.");
    }else{
        $("body").html("Not connected.");
    }
},1000);

I have angular controllers and modules in my project. Where should I put the code above? It should be executed in global context and not be assigned to a certain controller. Are there some kind of global controllers maybe?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First of all, I advise you to listen to online/offline events.

You can do it this way in AnguarJS:

var app = module('yourApp', []);

app.run(function($window, $rootScope) {
      $rootScope.online = navigator.onLine;
      $window.addEventListener("offline", function() {
        $rootScope.$apply(function() {
          $rootScope.online = false;
        });
      }, false);

      $window.addEventListener("online", function() {
        $rootScope.$apply(function() {
          $rootScope.online = true;
        });
      }, false);
});

NOTE: I am wrapping changing of root scope's variable in $apply method to notify Angular that something was changed.

After that you can:

In controlller:

$scope.$watch('online', function(newStatus) { ... });

In HTML markup:

 <div ng-show="online">You're online</div>
 <div ng-hide="online">You're offline</div>

Here is a working Plunker: http://plnkr.co/edit/Q3LkiI7Cj4RWBNRLEJUA?p=preview

Other solution could be to broadcast online/offline event. But in this case you need to initialize current status upon loading and then subscribe to event.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...