2015-10-15 150 views
1

我不知道为什么当我在html页面上打印json文件时,也可以从调用函数的按钮,但不在JavaScript文件中。Angularjs不加载json文件

这是一个问题,因为我需要对json文件中的数据进行排序,然后才能在网页中显示它,但我无法使其工作。我试图用这个解决方案https://stackoverflow.com/a/15463124/2796268, 但说没有定义

jsonDat控制台

我的代码:

$scope.init = function() { 

     console.log("init"); 
    $http.get('json/file.json') .success(function(data) { 
      $scope.jsonDat = res.data; 
     }) 
     .error(function(data,status,error,config){ 
      $scope.jsonDat = [{heading:"Error",description:"Could not load json data"}]; 
     }); 

    console.log(jsonDat); 

}; 

我怎么能在页面加载之前处理JSON数据或当页面正在加载?

+0

看起来像你想$ scope.jsonDat,而不是jsonDat。请记住,你将有权在保证成功回调的情况下访问它,但在其他任何地方它必须被视为异步变量(它可能为空或它可能被解析的数据) – Hypaethral

+0

@GrumbleSnatch好吧,它现在有点用了,但它打印一个空数组 –

回答

2

试试这个:

$scope.init = function() { 

    console.log("init"); 
    $http.get('json/file.json').success(function(data) { 
      $scope.jsonDat = data; 
      console.log($scope.jsonDat); 
     }) 
     .error(function(data, status, error, config) { 
      $scope.jsonDat = [{ 
       heading: "Error", 
       description: "Could not load json data" 
      }]; 
      console.log($scope.jsonDat); 
     }); 

}; 

在你有数据成功,但尝试从res.data得到。当你使用成功的时候,它不会回应数据,而只会回应你的数据。

3

可以处理数据时,它是从$http返回,就像这样:

$scope.init = function() { 
    $http.get('json/file.json').success(function(data) { 
     //---- SORT HERE ---- 
     $scope.jsonDat = mySortFunction(data); 
    }); 
}; 
1

我以为你想排序一些JSON文件,然后显示在HTML页面。所以我的想法是获取JSON文件(你试过)

$http.get('json/file.json') .success(function(data) { 
     $scope.jsonDat = data.res; 
     console.log('Checking the result',angular.toJson($scope.jsonDat)); 
    }) 

但是把你的结果

$scope.jsonDat = data.res; 

例如,

sortService.sortJsn = data.res; 

$ scope.jsonDat而是创建角服务将数据倒入那里,然后您可以访问这些数据在你的控制器中排序它也显示在HTML中。