I have built a simple AngularJS script that I would like to call a JSON packet every 10 seconds or so and update the variables. When I leave it outside of a pull data function it works. I can post the app.controller part and it works. Even if I pasted it five times and change the last one. Figured I'd asked here.
First here is the JSON I am pulling
{"FirstName":"Test","LastName":"Test"}
Here is the script code:
<script>
// AngularJS - Init app variable
var app = angular.module("MyApp", []);
// AngularJS - Set default values to AngularJS variables
app.controller("MyCTRL", function ($scope) {
$scope.FirstName = "-";
$scope.LastName = "-";
});
var getJSON = function (url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("get", url, true);
xhr.responseType = "json";
xhr.onload = function () {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
function pulldata() {
getJSON("<thejsonurl>",
function (err, data) {
if (err != null) {
//error has happened
} else {
app.controller("MyCTRL", function ($scope) {
$scope.FirstName = data.FirstName;
$scope.LastName = data.LastName;
});
}
});
}
//timer function for loading in page data
function pagetimer() {
setTimeout(function() { pulldata(); pagetimer(); }, 10000); // 10000 = 10 seconds
}
//Pull data as soon as webpage is up
pulldata();
//Start timer for data refresh
pagetimer();
Here is the HTML part:
<div ng-app="MyApp" ng-cloak ng-controller="MyCTRL">
FirstName: {{FirstName}}
LastName: {{LastName}}
</div>
Just a FYI. Verified the JSON URL is working. When I do an alert(data.FirstName); in the embedded function. It does return the first name. The code just does not update FirstName in the MyApp Div.