【问题标题】:How to retrieve data from Json using AngularJS?如何使用 AngularJS 从 Json 中检索数据?
【发布时间】:2015-08-22 21:14:29
【问题描述】:

我最近尝试使用 AngularJS 从 JSON 文件中检索数据。但是我不知道该怎么做;我尝试过这样做,但它不起作用,有人可以告诉我哪里出错了吗?

<div ng-repeat="stuff in otherStuff">
  <p>Title: {{stuff.name}}</p>
  <p>Url: {{stuff.url}}</p>
</div>

数据控制器:

$scope.otherStuff = {};
jsonFactory.getOtherStuff()
  .then(function (response) {
    $scope.otherStuff = response.data.components;
  }, function (error) {
    console.error(error);
  });

jsonFactory:

angular.module('generatorMeanstackApp')
  .factory('jsonFactory', function ($q, $http) {
    return {
      getOtherStuff: function () {
        var deferred = $q.defer(),
          httpPromise = $http.get('data.json');

        httpPromise.then(function (response) {
          deferred.resolve(response);
        }, function (error) {
          console.error(error);
        });

        return deferred.promise;
      }
    };
  });

我的 JSON 数据示例:

{
  "name": "Blogs",
  "url": "blogs.my-media-website.com/*",
  "dependsOn": ["Wordpress MU"],
  "technos": ["PHP", "Wordpress"],
  "host": { "Amazon": ["?"] }
},

【问题讨论】:

  • otherStuff 返回的 JSON 是什么?
  • 第一眼看起来不错。控制台有错误吗?

标签: javascript html arrays json angularjs


【解决方案1】:

在您的控制器中,对数据的引用(通过服务)嵌套得太深,应该是:

$scope.otherStuff = response.data;

代替:

$scope.otherStuff = response.data.components;

您可以将 JSON 包装在一个数组中:

[
  {...},
  {...},
  {...}
]

另外,如果您使用 yeoman 搭建脚手架,data.json 需要在 app/ 路线中。如果它在路线之外,您将收到 404。

【讨论】:

  • @benGshore 抱歉,范围绑定应该是 $scope.otherStuff = response.data; - 更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 2020-01-23
  • 1970-01-01
相关资源
最近更新 更多