简体   繁体   English

如何访问嵌套的JSON数据?

[英]How to access Nested JSON Data?

I'm having trouble displaying Nested JSON with ng-repeat. 我在显示带有ng-repeat的嵌套JSON时遇到问题。 I have a List of cars assigned to a person for a particular month. 我有一个特定月份分配给某人的汽车清单。 If you search April you will get April data. 如果您搜索四月,您将获得四月数据。 Click on the Name and it should populate Car section. 单击名称,它将填充“汽车”部分。 Here's pluker . 这是普鲁克 I have two functions one for the search button and the other for row click. 我有两个功能,一个用于搜索按钮,另一个用于行单击。 Can someone tell me the proper way to push the nested car info? 有人可以告诉我正确的方法来推送嵌套的汽车信息吗? Car info is in Results. 汽车信息在结果中。

    $scope.results = [];
    $scope.clickButton = function (enteredValue) {

    $scope.items = $scope.info;


    angular.forEach($scope.items[enteredValue], function (item, key) {
        $scope.results.push({
                 name: item.Name,
                 address: item.Address,
                 phone: item.Phone, 
                 status: item.Status,
                 cars:item.Cars
             });
     });
    };

   $scope.cars = [];

   $scope.clickButton2 = function () {

    $scope.rowItems = $scope.info.Cars;

    angular.forEach($scope.rowItems, function(car, key){
        $scope.cars.push({

            vehicleMake: car.Make,
                vehicleYear: car.Year
        });
         });
};

The easiest way to implement this is by leveraging the $index scope variable set by ngRepeat (see the docs ). 实现此目的的最简单方法是利用ngRepeat设置的$index作用域变量(请参阅docs )。 This lets you pass the index of the result item to the controller method so that it knows which result to read the cars from: 这使您可以将结果项的索引传递给controller方法,以便它知道从哪个结果读取汽车:

<tr ng-repeat="result in results">
  <td ng-click='showCars($index)'>{{result.name}}</td>
  <td>{{result.address}}</td>
  <td>{{result.phone}}</td>
  <td>{{result.status}}</td>
</tr>

You can then use the index like this: 然后,您可以像这样使用索引:

$scope.showCars = function(resultIndex) {
  $scope.cars = $scope.results[resultIndex].cars;
}

And finally display $scope.cars on the page: 最后在页面上显示$scope.cars

<table>
  <tr>
    <th>Car</th>
    <th>Year</th>
  </tr>
  <tr ng-repeat="car in cars">
    <td>{{Make}}</td>
    <td>{{Year}}</td>
  </tr>
</table>

One more thing: for array transformations such as the attribute lower-casing in your example code, consider using the Array map() method instead of angular.forEach() . 还有一件事:对于数组转换(例如,示例代码中的属性低壳),请考虑使用Array map()方法而不是angular.forEach() Here is an example: 这是一个例子:

$scope.cars = $scope.results[resultIndex].cars.map(function(car) {
  return {
    make: car.Make,
    year: car.Year
  };
};

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

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