var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.model = {
pingState: 'unsent'
};
// Presuming a server running locally at port 8080
ping('localhost:8080/!none.png', function callback (response, e) {
$scope.model.pingState = response;
console.log(response);
console.log(e);
$scope.$apply();
});
function ping(ip, callback) { // via http://jsfiddle.net/GSSCD/203/
if (!this.inUse) {
this.status = 'unchecked';
this.inUse = true;
this.callback = callback;
this.ip = ip;
var _that = this;
this.img = new Image();
this.img.onload = function () {
_that.inUse = false;
_that.callback('responded');
};
this.img.onerror = function (e) {
if (_that.inUse) {
_that.inUse = false;
_that.callback('error', e);
}
};
this.start = new Date().getTime();
this.img.src = "http://" + ip;
this.timer = setTimeout(function () {
if (_that.inUse) {
_that.inUse = false;
_that.callback('timeout');
}
}, 1500);
}
}
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script data-require="jquery@*" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Ping Status: {{model.pingState}}</p>
<div style="background-color:red; width:128px; height:128px;" ng-if="model.pingState != 'responded'"></div>
<div style="background-color:green; width:128px; height:128px;" ng-if="model.pingState == 'responded'"></div>
</body>
</html>