1

i am using the below format to get a JSON object from my localhost. The JSON is pretty complicated and lengthy so , using jquery to populate the HTML is getting complicated.

function processmsg(msg) {
        var jobj = JSON.parse(msg);
        if (typeof jobj === 'object')
        {
            // Parse the JSON
            }
            document.getElementById("messages").innerHTML = globalTag;

        }
    }

    function waitForMsg() {
        $.ajax({
            type: "GET",
            url: "1.json",

            cache: false,
            timeout: 50000,

            success: function (data) {
                processmsg(data);
                if (!data) {
                    setTimeout(
                        waitForMsg,
                        1000
                    );
                };
            },

            error: function (XMLHttpRequest, textStatus, errorThrown) {

                setTimeout(waitForMsg, 15000);
                processmsg("error");
            }

        });
    };

    $(document).ready(function () {
        waitForMsg();
        processmsg("loading");
    });

I would like to use the format like {{jobj.entries}}. something like this. This can be done on angularJS. can you guys please suggest me how to do the same in angular ?

i want to query the JSON every 1 min and when the data is found i want to cancel the interval. I dono how to do it in angularjs.

==================update================ i got below code snippet. It is working fine, But how do i stop the url query once the json object is obtained..

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

    app.controller('jsonController', function($scope, $http) {

      $scope.getData = function(){
        var url = "{% static "" %}tmp/{{url_hash}}/{{url_json}}";
        $http.get(url)
          .success(function(data, status, headers, config) {
            console.log(data);
          });
      };
      if (!$scope.data){
        setInterval($scope.getData, 2000);
      }

The issue here is the json object will be available after 3 sec only.

3
  • You shoul play with angular.js before starting an app. Read documentations, try create simple aplication, hello world app, use $http, $timeout, dependency injection etc. I think it is not the right time to start developing app with angular.js Commented Jan 5, 2015 at 16:56
  • I got the below code snippet.added to the description Commented Jan 5, 2015 at 16:58
  • Why do you need using interval? Angular.js has own $interval service please look at this page, Also, you should set $scope.data = data in success function and cancel the interval promise if success Commented Jan 5, 2015 at 17:07

3 Answers 3

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

app.controller('jsonController', ['$scope','$http','$timeout',function($scope, $http, $timeout) {

  $scope.getData = function(){
    var url = "{% static "" %}tmp/{{url_hash}}/{{url_json}}";
    $http.get(url)
      .success(function(data, status, headers, config) {
          if(!data)
             $timeout(function(){
                $scope.getData()
             }, 2000)
          else{
             $scope.myData = data.data? data.data:data;
             $scope.showError = false;
          }


      })
       .error(function(msg) {
          $timeout(function(){
              $scope.getData()
          }, 2000)
          $scope.processMessage(msg)
      });
  };
  $scope.processMessage = function(msg){
      if(angular.isString(msg))
       $scope.errorMessage = msg;
     else if(angular.isObject(msg)){
        $scope.errorMessage = msg.message // the property you want;
     }
     $scope.showError = true;
  }
  $scope.getData();
}])

HTML:

 <div ng-controller="jsonController">
      <div ng-show="showError">
        {{errorMessage}}
      </div>
      <div id="myDatacontainer">
           //you can bind any propery of your data by using angular direvtives
           //look at ng-bing, ng-if etc. directives
          {{myData.name}} ...
      </div>
 </div>

Hope it help.

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

2 Comments

data.data? data.data:data what does this mean ? the loop terminates as expected. THanks a lot.
sometime server response expected data properties as child propery. Just check if is child or not. Complately depends on your data structure.
1

Consider you have following JSON data stored in a scope variable named data:

$scope.data = {
  "array": [
    1,
    2,
    3
  ],
  "boolean": true,
  "null": null,
  "number": 123,
  "object": {
    "a": "b",
    "c": "d",
    "e": "f"
  },
  "string": "Hello World"
}

Then you write your HTML in the following way like:

<div>
    Boolean: {{data.boolean}}
</div>
<div>
    Number: {{data.number * 2}}
</div>
<div>
    Array:
    <p ng-repeat="(key, value) in data.object"> {{key}} : {{value}}</p>
</div>
Another way to bind <div ng-bind="data.string"></div>

Here you can stop your call. You can use enhanced angular service $interval for this:

$scope.getData = function(){
    var url = "{% static "" %}tmp/{{url_hash}}/{{url_json}}";
    $http.get(url)
    .success(function(data, status, headers, config) {
        console.log(data);
        $interval.cancel($scope.intervalObject);    // cancel the interval when data is loaded
     });
};

if (!$scope.data){
    $scope.intervalObject = $interval($scope.getData, 2000);
}

4 Comments

The problem is , i have a jquery. I am unable to pass the json data to Angular $scope.
Then use angular's $http service for AJAX call.
thats the help i need. The angular code which i metioned above works . But it keeps on querying. I need to stop it once the data is available. i dono how to do that.
for some reason i get this error. :(Uncaught Error: [$injector:modulerr] errors.angularjs.org/1.3.8/$injector/……ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.8%2Fangular.min.js%3A17%3A350)
0
  if (!$scope.data){
    setInterval($scope.getData, 2000);
  }

since $scope.data is not set it'll continue calling the request(since you are not setting $scope.data anywhere).

Edit: Also, use angularjs $interval since it's the angular way of using setInterval and it keeps track of the $digest cycle

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.