简体   繁体   English

AngularJs读取json文件

[英]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. 我有一棵用json动态创建的树。有一个控制器,并且在该控制器中有一个json数组。我使用此json创建一棵树,但我需要从文件外部读取此json。

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); Json数组读取部分(在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? 我想调用json文件并读取它以创建树。如何调用json文件并读取angularjs?

Reading JSON in Angular is pretty straightforward with $http. 使用$ http在Angular中读取JSON非常简单。 Keep in mind that $http will return a promise, and you need to resolve it before processing. 请记住,$ http将返回一个承诺,并且您需要在处理之前解决它。

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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