1

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.

2
  • 1
    You need to read an AngularJS tutorial. You can't redefine a controller once the application has started. Angular has an $http service that you should use. It has a $timeout service that you should use. Code should be inside angular components, not in global functions. Commented Jun 21, 2016 at 21:30
  • 1
    While Angular might seem foreign at first, if you want to use it successfully you need to really embrace it. JB is absolutely correct. Start with a straightforward, basic tutorial and focus on learning and understanding the fundamentals. There are too many core issues with what you're doing currently to properly fix the problems you are having. Commented Jun 21, 2016 at 21:38

1 Answer 1

0

To help, here is one solution to your problem I posted on plunker . You will see the content updated after 2 seconds and then, you can look at the console to see the different calls at 2 second intervals.

I use $interval to call the getJSON function every 2 seconds:

vm.promise=$interval(vm.getJSON, 2000);

The get JSON uses $http:

vm.getJSON = function() {
    vm.iterations--;
    if (vm.iterations < 1 ) {
      $interval.cancel(vm.promise);
      console.log('Stopped interval calls ');
    }
    $http({
      method: 'GET',
      url: 'data.json'
    }).then(function successCallback(response) {
      // this callback will be called asynchronously
      // when the response is available
      console.log('Success '+JSON.stringify(response));
      vm.FirstName = response.data.FirstName;
      vm.LastName = response.data.LastName;
    }, function errorCallback(reason) {
      // called asynchronously if an error occurs
      // or server returns response with an error status.
      console.log('ERROR: '+JSON.stringify(reason));
    });
  }

Note that on success, we do not create a new controller, but update the variables FirstName and LastName:

 }).then(function successCallback(response) {
      // this callback will be called asynchronously
      // when the response is available
      console.log('Success '+JSON.stringify(response));
      vm.FirstName = response.data.FirstName;
      vm.LastName = response.data.LastName;
    },

I created a variable iterations that indicates how many times we will call getJSON:

 vm.iterations = 3;  // Number of calls to the function

And I stop the iterations using $interval.cancel.

Here is the full app.js

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $http, $interval) {
  var vm = this;
  vm.FirstName = '-';
  vm.LastName = '-';
  vm.name = 'World';
  vm.iterations = 3;  // Number of calls to the function

  vm.getJSON = function() {
    vm.iterations--;
    if (vm.iterations < 1 ) {
      $interval.cancel(vm.promise);
      console.log('Stopped interval calls ');
    }
    $http({
      method: 'GET',
      url: 'data.json'
    }).then(function successCallback(response) {
      // this callback will be called asynchronously
      // when the response is available
      console.log('Success '+JSON.stringify(response));
      vm.FirstName = response.data.FirstName;
      vm.LastName = response.data.LastName;
    }, function errorCallback(reason) {
      // called asynchronously if an error occurs
      // or server returns response with an error status.
      console.log('ERROR: '+JSON.stringify(reason));
    });
  }

  vm.promise=$interval(vm.getJSON, 2000);


});

The HTML looks like this:

<!DOCTYPE html>
<html ng-app="plunker">

(...)
  <body ng-controller="MainCtrl as vm">
    <p>Hello {{vm.name}}!</p>
    <div>
      <P>
      FirstName: {{vm.FirstName}} 
      </P>
      <P>
      LastName: {{vm.LastName}}
      </P>

    </div>
  </body>

</html>

And I created a JSON file called data.json.

Hope this helps. Let us know.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.