简体   繁体   中英

AngularJs read json file

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?

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 **/
});

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM