David Gourde
David Gourde

Reputation: 3914

Use json as a data source when creating an Angular Tree Control

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?

Upvotes: 0

Views: 175

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 37918

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

Upvotes: 1

Related Questions