简体   繁体   English

使用AngularJS访问和显示JSON对象

[英]Accessing and Displaying JSON Object with AngularJS

I'm trying to access an object in JSON with AngularJS, and display the values. 我正在尝试使用AngularJS访问JSON中的对象,并显示值。 I have done this when I create an array in JSON but this time I want to show an example with an object. 我在JSON中创建数组时已经完成了此操作,但是这次我想显示一个带有对象的示例。 This is my code: 这是我的代码:

My JSON File 我的JSON文件

{ "user": {
"Name":"Ben", 
"City":"New York"}}

My angular app 我的角度应用

var app = angular.module('myApp', []);

    app.controller('jsonObjectExample', function($scope, $http) {
      $http.get("jsonobject.json").then(function (response) {
          $scope.myData = response.data.user;
      });
    });

My HTML 我的HTML

<body>
    <div ng-app="myApp" ng-controller="jsonObjectExample"> 
      <ul>
        <li ng-repeat="x in myData">
          {{ x.Name + ', ' + x.City }}
        </li>
      </ul>
    </div>
  </body>

Here is a link to these files on plunker: https://plnkr.co/edit/uBRf99AjYH9zX0WuHsW3?p=preview 这是在plunker上这些文件的链接: https ://plnkr.co/edit/uBRf99AjYH9zX0WuHsW3 ? p = preview

Can someone explain where I'm going wrong? 有人可以解释我要去哪里了吗? Thanks. 谢谢。

remove the ng-repeat. 删除ng-repeat。 myData is object, not an array so no need to use the ng-repeat myData是对象,而不是数组,因此无需使用ng-repeat

  <body>
    <div ng-app="myApp" ng-controller="jsonObjectExample"> 
      <ul>
        <li >
          {{ myData.Name + ', ' + myData.City }}
        </li>
      </ul>
    </div>
  </body>

Demo 演示版

If you are using ng-repeat make sure the json which you are parsing should give some array value. 如果您使用的是ng-repeat,请确保要解析的json应该提供一些数组值。

you can correct your json like: 您可以像这样更正您的json:

{ "user": [{
"Name":"Ben", 
"City":"New York"}]}

Other codes are working fine. 其他代码工作正常。 Please check this 请检查一下

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM