0

I am using Angular Tree Control to build a tree and I would like to use a json file as the data source.

This is my HTML tag

<treecontrol class="tree-classic"
     tree-model="treedata"

And this is my javascript code to get the json file as an object

var JSON;
$.getJSON('data.json', function(response){
    JSON = response;
    alert(JSON.property);
 });
 $scope.treedata = JSON;

The path should be correct (there is only two files for my test, an index.html and the data.json both in the same folder). If I take the content of my json file and I simply paste it in a variable to get the object, it works. But when I read the file, the alert says that my JSON variable is empty.

Would you have an idea on how to fix this? Thank you very much.


Update

Following the idea of callbacks, I found this solution.

$.getJSON('data.json', function(response){
    $scope.$apply(function() { 
         $scope.treedata = response;
    });
});

Is there a better way to do this?

1
  • why alert(JSON.property) is used. why not just alert(JSON)? Commented Jul 26, 2016 at 14:31

1 Answer 1

1

You're assigning $scope.treedata before $.getJSON completed. You should do it in success callback:

$.getJSON('data.json', function(response){
   $scope.$apply(function() { 
      $scope.treedata = response;
   });
});

You could use $scope.$apply in order to update bindings, but it is better to use $http service instead of $.getJSON

$http.get('data.json').then(function(response){
    $scope.treedata = response.data;
});

Don't forget to inject $http first

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

2 Comments

I tried but only got an empty tree. It seems the tree got the data correctly, but it does not show up. But it show up if I give it a json object. :S
I've added some informations. The callback helped, but it was not enough. Is there a way to do better than my $scope.$apply?

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.