簡體   English   中英

如何使用AngularJS從Json檢索數據?

[英]How to retrieve data from Json using AngularJS?

我最近嘗試使用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": ["?"] }
},

在您的控制器中,對數據的引用(通過服務)嵌套得太深,應為:

$scope.otherStuff = response.data;

代替:

$scope.otherStuff = response.data.components;

您可以將JSON包裝在數組中:

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

此外,如果您使用yeoman data.json支架,則data.json必須位於app/路由中。 如果在路線之外,您會得到404。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM