如何使用AngularJS从Json中检索数据

How to retrieve data from Json using AngularJS?

本文关键字:检索 数据 Json 何使用 AngularJS      更新时间:2023-09-26

我最近尝试使用AngularJS从JSON文件中检索数据。但是我不知道该怎么做;我曾试图这样做,但它不工作,有人能告诉我我错在哪里?

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

DataController:

$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": ["?"] }
},

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

$scope.otherStuff = response.data;

代替:

$scope.otherStuff = response.data.components;

你可以把JSON包在一个数组中:

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

此外,如果您与约曼支架,data.json需要在app/路线上。