Just finished a Codeacademy tutorial using angular to loop through some JSON data from a URL and display the data.
Would love to know how to implement it so the data would be updated if the JSON data was changing periodically!
I know I need to maybe refresh the http get request,but after that I'm not sure.
If someone could point me in the right direction I would really appreciate it!
Thanks!
services/forecast.js
app.factory('forecast', ['$http', function($http) {
return $http.get('http://json-time.appspot.com/time.json')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
controllers/MinorController.js
app.controller('MinorController', ['$scope', 'forecast', function($scope, forecast) {
var setTimeOut = setInterval(function () {
forecast.success(function(data) {
$scope.fiveDay = data;
});
}, 5000);
$scope.$on('$routeChangeStart', function (scope, next, current) {
if (next.$$route.controller != "MinorController") {
clearInterval(setTimeOut); // clear interval here
}
});
}]);
test.html (view)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Angular -->
<script src="js/shared/angular.min.js"></script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="css/bootstrap.min.css">
<!-- Bootstrap JS -->
<script src="js/shared/bootstrap.min.js"></script>
</head>
<body ng-app="myApp">
<div class="container" ng-controller="MinorController">
<div class="row">
<h1>Time JSON Example</h1>
<h2>{{ fiveDay.tz }} </h2>
<h2> {{ fiveDay.hour }} </h2>
<h2> {{ fiveDay.datetime }} </h2>
<h2> {{fiveDay.second }} </h2>
</div>
</div>
<!-- Modules -->
<script src="js/app.js"></script>
<!-- Controllers -->
<script src="js/controllers/MainController.js"></script>
<script src="js/controllers/MinorController.js"></script>
<!-- Services -->
<script src="js/services/forecast.js"></script>
</body>
</html>
You can do it by using setInterval like so.
app.controller('MinorController', ['$scope', 'forecast', function($scope, forecast) {
var setTimeOut = setInterval(function () {
forecast.success(function(data) {
$scope.fiveDay = data;
});
}, 5000);
$scope.$on('$routeChangeStart', function (scope, next, current) {
if (next.$$route.controller != "MinorController") {
clearInterval(setTimeOut); // clear interval here
}
});
}]);
Now your service will call every 5 seconds and rebind your object.
If you go to another screen, then the routeChangeStart event will call for the interval to be cleared.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With