簡體   English   中英

AngularJs讀取json文件

[英]AngularJs read json file

我有一棵用json動態創建的樹。有一個控制器,並且在該控制器中有一個json數組。我使用此json創建一棵樹,但我需要從文件外部讀取此json。

我的控制器;

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

        }
    ],

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

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.........
                     }
                 }

我想調用json文件並讀取它以創建樹。如何調用json文件並讀取angularjs?

使用$ http在Angular中讀取JSON非常簡單。 請記住,$ http將返回一個承諾,並且您需要在處理之前解決它。

這是一個示例代碼:

$http.get('assets/messages.json').then(function (data) {
            /** work with data **/
});

在這里,您可以獲得有關您的問題的完整教程。 您只需要以自己的方式對其進行修改。

 <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