0

I have a tree which is created dynamically with json.There is a one controller and in this controller there is a json array.I use this json to create a tree,but i need to read this json from file externally.

My controller;

..........
$scope.myjson = 
{       
    "option1": [
        {   
            "child":[{"label":"Test1" },{"label":"Test2"}],
            "id": "option1"

        }
    ],

"option2": [
        {   
            "child":[{"label":"Test1.1",}],
            "id": "option2"
        }
    ],
   ...........
   }

Json array reading part(In Controller);

angular.forEach($scope.myjson, function(value, key) 
        {
         if (key === 'option1') 
                {
                for(var t=0;t<$scope.myjson[key][0].child.length;t++)
                    {
                     ......Somethings.........
                     }
                 }

I want to call json file and read it to create a tree.How can i call json file and read in angularjs?

4
  • 1
    Did you check $http.get? Commented Apr 28, 2015 at 6:03
  • What have you done so far? Commented Apr 28, 2015 at 6:04
  • i have tried $http.get before but i could not solve the problem ,could you give me an example jsfiddle? Commented Apr 28, 2015 at 6:08
  • @user4773604 You can find example in the answer posted. Commented Apr 28, 2015 at 6:32

2 Answers 2

2

Reading JSON in Angular is pretty straightforward with $http. Keep in mind that $http will return a promise, and you need to resolve it before processing.

Here is a sample code:

$http.get('assets/messages.json').then(function (data) {
            /** work with data **/
});
Sign up to request clarification or add additional context in comments.

1 Comment

could you give me an example similar to my task
0

Here you can get a complete tutorial regarding your problem. You just need to modify it in your way.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="customersCtrl"> 

<ul>
  <li ng-repeat="x in names">
    {{ x.Name + ', ' + x.Country }}
  </li>
</ul>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
    $http.get("http://www.w3schools.com/angular/customers.php")
    .success(function(response) {$scope.names = response.records;});
});
</script>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.