我是Angular js的新手,我想在HTML文件中显示本地JSON数据.下面是我试过的代码

I'm new to Angular js, I want to display the local JSON data in the HTML file. Below is the code I tried

本文关键字:数据 JSON 代码 新手 js Angular 我是 文件 HTML 显示      更新时间:2023-09-26

我有一个示例JSON文件text.json。我想使用ng-repeat在HTML中显示数据,但它不起作用。

下面是我的代码:
<html ng-app="myapp">
    <head>
        <title> Test</title>
        <script src="js/angular.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            var myapp = angular.module('myapp', []);
            myapp.controller('myCtrl', function ($scope, $http) {
                $http.get("js/text.json").success(function (response) {
                    $scope.names = response;
                });
            });
        </script>
    </head>
    <body>
        <div ng-controller="myCtrl">
            <li ng-repeat="value in names">
                {{value.name +' and the age is ' + value.age}}
            </li>
        </div>
    </body>
</html>

有什么建议吗?

想法1

JSON文件可能无效。通过删除最后一个逗号来编辑它:

[
  {
    "name": "test",
    "age": 28
  },
  {
    "name": "test1",
    "age": 28
  },
  {
    "name": "test2",
    "age": 28
  },
  {
    "name": "test4",
    "age": 28
  },
  {
    "name": "test3",
    "age": 28
  }
]

想法二

再次检查JSON文件的路径。js/text.json真的是正确的吗?

想法三

你是否使用一些web服务器在浏览器中显示你的文件?它可能不会通过文件协议(例如file:///myfile.html)工作,你需要一个web服务器和http协议(例如http://localhost:9000)。

想法4

如果你使用的是历史版本的AngularJS,可能会有插值问题。

{{}}是AngularJS插值的标记——它意味着你可以显示任何存在于Angular作用域中的值。您正在创建一个ng-repeat。相比之下,"and the age is"是一个简单的文本,不需要插值(它在Angular的作用域中不是变量,而是一个简单的常量)。

这意味着你只需要插入{{value.name}}{{value.age}}。它应该使用下面的代码:

<div ng-controller="myCtrl">
   <li ng-repeat="value in names">
      {{value.name}} and the age is {{value.age}}
   </li>
</div>

改为"{{value.name}},年龄为{{value。age}}"只有当json数据正确时。

请将'controller'和'app.js'文件分开,以便轻松识别问题。

    return $http
                                        .get(
                                                'http://localhost:8089/eCommerce/product/attributes/'
                                                        )
                                        .then(
                                                function(response) {
                                                    return response.data;
                                                },
                                                function(errResponse) {
                                                    console
                                                            .error('Error while fetching specific Item');
                                                    return $q
                                                            .reject(errResponse);
                                                });
                            }