如何使用AngularJS以正确的方式显示Json文件中的数据

how to show data from Json file in correct way with AngularJS

本文关键字:Json 显示 文件 数据 方式 AngularJS 何使用      更新时间:2023-09-26

我需要从下面的json文件中获取数据(请单击"json文件"链接查看json文件的结构如何),但我不知道应该在"$Scope.listOfRecipe="后面放什么,我放了response.data.recipes,但它在这里不起作用,而且有一些错误。

angular.js:12520 TypeError: Cannot read property 'recipes' of undefined at recipesController.js:10 at angular.js:10296 at angular.js:14792 at r.$eval (angular.js:16052) at r.$digest (angular.js:15870) at r.$apply (angular.js:16160) at g (angular.js:10589) at T (angular.js:10787) at XMLHttpRequest.w.onload (angular.js:10728)

Json文件这里是我的Json文件

这是我的recipesControllers.js

var myApp = angular.module('myApp', []);
 myApp.controller('namesCtrl',function ($scope, $http) {
$scope.listOfRecipe = null;
$http.get('http://164.132.196.117/chop_dev/recipe/recipes.json')
     .success(function (response) {
         $scope.listOfRecipe = response.data.recipes;
     })
});

这是我的Index.html

<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
<body>
  <div ng-app="myApp" ng-controller="namesCtrl">
    <ul>
      <li ng-repeat="x in listOfRecipe ">
        {{ x.Recipe.id + ', ' + x.Recipe.name }}
      </li>
    </ul>
  </div>
  <script src="C:/Users/Enetfirm  Server/Desktop/AngularJs/recipesController.js"></script>
</body>
</html>

您可以console.log(response)并查看响应,并相应地调整代码。

但我建议使用标准的承诺模式:

$http.get('http://164.132.196.117/chop_dev/recipe/recipes.json')
  .then(function(resp) {
    $scope.listOfRecipe = resp.data.recipes;
  })
  .catch(function(errResp) {
    // catch error
  })
  .finally(function() {
    // when it is done do something in the view
    // remove a spinner gif or scroll to top ...
  });

您能在开发者工具-网络选项卡上验证文件是否正在下载吗?

请确保它正常工作,并请console.log response和response.data以便在那里验证它!

这是一个Json文件,意味着响应是Json本身,而不是res.data

请检查并回复以共享您的解决方案