【问题标题】:Angularjs not loading json filesAngularjs不加载json文件
【发布时间】:2016-01-14 06:37:19
【问题描述】:

我不确定为什么当我在 html 页面上打印 json 文件时,也可以通过调用函数的按钮,但不在 javascript 文件内部。

这是一个问题,因为我需要先对 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 数据?

【问题讨论】:

  • 看起来你想要 $scope.jsonDat,而不是 jsonDat。请记住,您可以在保证成功的回调中访问它,但在其他任何地方都必须将其视为异步变量(它可以为 null 或者可以解析数据)
  • @GrumbleSnatch 好的,它现在可以工作了,但它会打印一个空数组

标签: javascript json angularjs


【解决方案1】:

当数据从$http返回时,可以进行处理,如下:

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

【讨论】:

    【解决方案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】:

      我以为您想对一些 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 改为创建 angular service 将您的数据倒在那里,然后您可以在控制器中的任何位置访问这些数据并对其进行排序在 HTML 中显示它。

      【讨论】:

        猜你喜欢
        • 2016-10-27
        • 1970-01-01
        • 1970-01-01
        • 2016-02-06
        • 2017-05-01
        • 2017-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多